language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include<stdio.h> int main(void) { char xd[1] = {"5"}; int number = xd[0] - '0'; printf("\n%d\n", number); return 0; }
C
// // mysortstr.c // lambda // // Created by Ксения Афанасьева on 12.11.17. // Copyright © 2017 Ксения Афанасьева. All rights reserved. // #include "mysortstr.h" int mysortstr(char arr[][STR_MAX_LENGTH], int n) { if(n <= 0) { return 1; } for(int i = 0; i < n-1; i++) { for(int j = i+1; j < n; j++) { if(stringcompare(arr[i], arr[j]) == 1) { stringswap(arr[i], arr[j]); } } } return 0; }
C
#include <stdio.h> void func(int a, int *b) { printf("%d %d\n", a, *b); } int main(void) { int x = 0; func(x++, &x); return 0; }
C
/* ============================================================================ Name : NKuckuckThreeNPlusOne.c Author : Nicholas Kuckuck Version : Copyright : Simplified BSD License Description : ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include <string.h> //===========Function Declarations=========================================== int computeMaxSequenceLength(int first, int last); int computeSequenceLength(int i); int computeNextValue(int v); //=========================================================================== int main(void) { //prompt for output filename, get range from stdin, print out to file setvbuf(stdout, NULL, _IONBF, 0); // Turn off output buffering. Required for automated testing. int first_value, last_value; int MaxSequenceLength; char out[200]; char buffer[BUFSIZ + 1]; // Reusable keyboard input buffer FILE *output; printf("Enter the output filename:\n"); gets(out); output = fopen(out, "w"); while (1) { first_value = atoi(gets(buffer)); if (strlen(buffer) == 0) { fclose(output); printf("Complete\n"); return EXIT_SUCCESS; } last_value = atoi(gets(buffer)); //printf("%d, %d", first_value, last_value); MaxSequenceLength = computeMaxSequenceLength(first_value, last_value); fprintf(output, "%d\t%d\t%d\n", first_value, last_value, MaxSequenceLength); } fclose(output); return EXIT_SUCCESS; } int computeMaxSequenceLength(int first, int last) { // takes range first - last, returns max sequence int i; int Seq_Len = 0; int lastSeqLen; int max = 0; //printf("%d, %d", first, last); for (i = first; i < last; i++) { //max = Seq_Len; Seq_Len = computeSequenceLength(i); if (Seq_Len > max) max = Seq_Len; //lastSeqLen = computeSequenceLength(++i); //if (Seq_Len > lastSeqLen) // max = Seq_Len; //printf("%d\n", Seq_Len); } //printf("%d, %d\n", Seq_Len, max); return max; } int computeSequenceLength(int i) { //takes number i, return sequence len of i int Seq_Len = 1; while (i != 1) { i = computeNextValue(i); ++Seq_Len; } return Seq_Len; } int computeNextValue(int v) { //takes number v returns nxt number in sequence if (v % 2) { v = (v * 3) + 1; } else v = v / 2; return v; }
C
#include<stdio.h> #include<stdint.h> #include<stdlib.h> #define NUMSAMPLES 100000 inline unsigned long long int count() __attribute__((always_inline)); inline unsigned long long int count() { unsigned int lo =0, hi=0; __asm__ __volatile__ ( // serialize "xorl %%eax,%%eax \n " ::: "%rax", "%rbx", "%rcx", "%rdx"); __asm__ __volatile__ ("rdtsc;" "mov %%eax, %0;" "mov %%edx, %1;" : "=r" ( lo ), "=r" ( hi ) ); return (unsigned long long int)hi<<32 | lo; } double getCounteroverhead() { int i = 0; unsigned long long int totalcount = 0; for (i=0;i<NUMSAMPLES; i++) { unsigned long long int start = count(); unsigned long long int end = count(); totalcount = totalcount + (end-start); } //printf("Tot: %llu\n\n", totalcount); return (double)totalcount/NUMSAMPLES; } int main() { unsigned long long int start = 0; unsigned long long int end = 0; int stride = 886432; int sample = 0; int numSamples = 1; double cumulativeReadTotal = 0; double cumulativeWriteTotal = 0; double totalReadcount = 0; double totalWritecount = 0; double counterOverHead = getCounteroverhead(); int i; int lo; int *a = NULL, *p = NULL, *tempPtr = NULL; int temp = 0; unsigned long long int numitems = 0; unsigned long long int numiters = 0; double cpuFreq = 2.3*1024*1024*1024; int incsize = 2*1024; unsigned long long int startsize = 1024*1024*1024; cumulativeReadTotal = 0; cumulativeWriteTotal = 0; for (sample = 1; sample <= numSamples; sample++) { numitems = startsize/sizeof(int*); // num of samples to run numiters = 1 * numitems; a = (int*)malloc(startsize); // calculate loop overhead start = count(); for (i=1; i<=numiters; i++) { } end = count(); lo = end - start - counterOverHead; printf("num iters: %llu\n", numiters); start = count(); for (i=0; i<numiters; i++) { //a[(i*stride)%numiters] = 540000000; //a[(i+stride)%numiters] = 540000000; a[i] = 540000000; } end = count(); totalWritecount = (end-start-counterOverHead-lo); cumulativeWriteTotal = cumulativeWriteTotal + totalWritecount; int t; start = count(); for (i=0; i<numiters; i++) { //t = a[(i*stride)%numiters]; //t = a[(i+stride)%numiters]; t = a[i]; } end = count(); totalReadcount = (end-start-counterOverHead-lo); cumulativeReadTotal = cumulativeReadTotal + totalReadcount; free(a); a = p = NULL; } double cyclesTakenWrite = cumulativeWriteTotal/numSamples; double timeTakeninSecWrite = cyclesTakenWrite/cpuFreq; double sizeinMB = (double)startsize/(1024*1024); double bandwidthWrite = sizeinMB/timeTakeninSecWrite; double cyclesTakenRead = cumulativeReadTotal/numSamples; double timeTakeninSecRead = cyclesTakenRead/cpuFreq; double bandwidthRead = sizeinMB/timeTakeninSecRead; printf("size: %f\tcyclesTaken: %f, %f\ttimeTaken: %f, %f\tbandwidth: %.20f\n", sizeinMB, cyclesTakenRead, cyclesTakenWrite, timeTakeninSecRead, timeTakeninSecWrite, bandwidthWrite); printf("Size=%llu\tRead BW=%.2f\tWrite BW=%0.2f\n", startsize, bandwidthRead, bandwidthWrite); return 0; }
C
#include <xc.h> //set the timer in pragma config #pragma config OSC = IRCIO, WDTEN = OFF //internal osciallator, WTD off //include the LEDout function void LEDout(int number) { LATC = (number & 0b00111100) << 2; //set all the C pins we want to be a 8bit number LATD = ((number & 0b11000000) >> 2) | ((number & 0b00000011) << 2); //just combine the part of the d reg split } //no need to define an integer here, we only have a timer overflow int timerOverflows = 0; //variables in the interrupts int timerStartValue = 3036; //calculated start value void delay(int t) { int x; for (x = 0; x < t; x++); } int bit16High(int x){//function to give the 8 most important bits of a 16 bit number x = x>>8; //keep high bits return x; } //function to give the 8 least important bits of a 16 bit number int bit16Low(int x) { x = x & 0b11111111; //keep low bits return x; } void interrupt InterruptHandlerHigh() { //high priority routine if (INTCONbits.TMR0IF) { timerOverflows++; //increment a counter LEDout(timerOverflows); TMR0L = bit16Low(timerStartValue); TMR0H = bit16High(timerStartValue); INTCONbits.TMR0IF = 0; //clear the interrupt flag } } void main(void) { OSCCON = 0x72; //8MHz clock while (!OSCCONbits.IOFS); //wait for osc to become stable //setup the outputs LATC = 0; //refresh LAT values LATD = 0; TRISD = 0; TRISC = 0; //set all pins as output // Generate an interrupt on timer overflow INTCONbits.GIEH = 1; // Global Interrupt Enable bit INTCONbits.TMR0IE = 1; //enable TMR0 overflow interrupt INTCON2bits.TMR0IP = 1; // TMR0 High priority //timer setup T0CONbits.TMR0ON = 1; //turn on timer0 T0CONbits.T016BIT = 0; // 8bit mode T0CONbits.T0CS = 0; // use internal clock (Fosc/4) T0CONbits.PSA = 0; // enable prescaler T0CONbits.T0PS = 0b100; // set prescaler value to 1:32 TMR0L = bit16Low(timerStartValue); TMR0H = bit16High(timerStartValue); while(1){} }
C
#include<stdio.h> /*˭Ȼõ˺֮͡*/ int main() { int jiu1,jiu2; /*jiu1׵Ⱦjiu2ҵȾ*/ int count[2]={0,0}; /*ҺȾ0ף1*/ int huihe; /*غ*/ int N1[200],N2[200]; /*廮ȭN1ףN2*/ int H1[200],H2[200]; /*庰H1,H2*/ int i; int sum[200]; /*㿴˭ֵ˱Ȼ*/ scanf("%d %d",&jiu1,&jiu2); scanf("%d",&huihe); for(i=0;i<200;i++) { H1[i]=0; N1[i]=0; H2[i]=0; N2[i]=0; } for(i=0;i<huihe;i++) { scanf("%d %d %d %d",&H1[i],&N1[i],&H2[i],&N2[i]); sum[i]=H1[i]+H2[i]; } /*Ϊжϲ*/ for(i=0;i<huihe;i++) { if(N1[i]==sum[i]&&N2[i]!=sum[i]) { count[0]++; if(count[0]>jiu1) { printf("A\n%d",count[1]); break; } continue; } else if(N2[i]==sum[i]&&N1[i]!=sum[i]) { count[1]++; if(count[1]>jiu2) { printf("B\n%d",count[0]); break; } continue; } } return 0; }
C
#include <unistd.h> //Provides API for POSIX(or UNIX) OS for system calls #include <stdio.h> //Standard I/O Routines #include <stdlib.h> //For exit() and rand() #include <pthread.h> //Threading APIs #include <semaphore.h> //Semaphore APIs sem_t cnt; int sum=0; void *thread(void *tmp) { sem_wait(&cnt); sum++; sem_post(&cnt); } void main() { pthread_t t; sem_init(&cnt, 0, 1); int i; int status = pthread_create(&t, NULL, (void*)thread, (void*)&i); pthread_join(t, NULL); printf("%d\n", sum); }
C
#include "../includes/setTabMenuHeight.h" int setTabMenuHeight(TabMenu *menu, unsigned int height) { if (!menu) { fputs("Error : No menu provided\n", stderr); return (0); } menu->menu_pos.h = height; menu->tab_content_pos.h = height - (menu->header_pos.h + menu->tabs_preview_pos.h); return (1); }
C
#ifndef MLALIGN_INIT_SIMDWRAPPER_H #define MLALIGN_INIT_SIMDWRAPPER_H #include <assert.h> #ifdef SIMD_ARCH_X86_SSE3 #include <xmmintrin.h> const size_t VECSIZE = 2; typedef __m128d dvec; #elif defined(SIMD_ARCH_X86_AVX) #include <immintrin.h> const size_t VECSIZE = 4; typedef __m256d dvec; #else #error("Specify a simd architecture (SIMD_ARCH_X86_SSE3 or SIMD_ARCH_X86_AVX)") #endif static inline dvec maxdvec(dvec a, dvec b) { #ifdef SIMD_ARCH_X86_SSE3 return _mm_max_pd(a, b); #elif defined(SIMD_ARCH_X86_AVX) return _mm256_max_pd(a, b); #endif } static inline dvec loaddvec(double* src) { #ifdef SIMD_ARCH_X86_SSE3 return _mm_loadu_pd(src); #elif defined(SIMD_ARCH_X86_AVX) return _mm256_loadu_pd(src); #endif } #ifdef SIMD_ARCH_X86_AVX const static __m256i STORE_MASKS[] = { _mm256_set_epi64x( 0, 0, 0, 0), // This should not be accessed anyway, just for padding _mm256_set_epi64x( 0, 0, 0, ~0), _mm256_set_epi64x( 0, 0, ~0, ~0), _mm256_set_epi64x( 0, ~0, ~0, ~0), }; #endif static inline void storedvec(double* dest, dvec src, size_t n) { assert(n > 0); assert(n <= VECSIZE); // This is forbidden as part of the contract. #ifdef SIMD_ARCH_X86_SSE3 if (n == 2) { _mm_storeu_pd(dest, src); // Most likely case first } else if (n == 1) { _mm_storel_pd(dest, src); } #elif defined(SIMD_ARCH_X86_AVX) if (n == VECSIZE) { _mm256_storeu_pd(dest, src); } else { _mm256_maskstore_pd(dest, STORE_MASKS[n], src); } #endif } #endif /* end of include guard: MLALIGN_INIT_SIMDWRAPPER_H */
C
#include<stdio.h> void reverse(long long int n,long long n1,long long int i) { long long int rev=0,rem; while(n!=0) { rem=n%10; rev=rev*10+rem; n=n/10; } if(rev!=n1) { n=rev+n1; n1=n; i=i+1; reverse(n,n1,i); } else printf("%lld %lld\n",i,rev); } int main() { long long int i=0,j=0,t,n,n1; scanf("%lld",&t); for(j=0;j<t;j++) { scanf("%lld",&n); n1=n; reverse (n,n1,i); } return 0; }
C
"'You are provided with a number "N", Find the Nth term of the series: 1, 4, 9, 25, 36, 49, 64, 81, ....... (Print "Error" if N = negative value and 0 if N = 0). Input Description: An integer N is provided to you as the input. Output Description: Find the Nth term in the provided series. Sample Input : 18 Sample Output : 324"' #include <stdio.h> int main() { int n,i; scanf("%d",&n); i=n*n; printf("%d",i); return 0; }
C
#define _CRT_SECURE_NO_WARNINGS #include<Windows.h> #include<stdio.h> #pragma once //!@brief FU蕪Ɏgp}N enum E_COLOR{ BLUE = 0, //!< GREEN, //!< RED //!< }; //!@brief 摜̏c̍őTCY //!@details Ŏw肷邱 #define IMAGE_HEIGHT 50 //!@brief 摜̉̍őTCY //!@details Ŏw肷邱 #define IMAGE_WIDTH 50 //!@brief `ʐ̏c̍őTCY #define SCREEN_HEIGHT 100 //!@brief `ʐ̉̍őTCY #define SCREEN_WIDTH 100 //!@brief 摜̏\ typedef struct{ COORD halfSize; //!<摜̔̑傫 CHAR_INFO imageData[IMAGE_HEIGHT][IMAGE_WIDTH]; //!<摜iFjێ }tagIMAGE_INFO; //!@brief `ʐ̏\ //!@details ȉpbgƌĂ typedef struct { CHAR_INFO ScreenInfo[SCREEN_HEIGHT][SCREEN_WIDTH]; //!<XN[ɓ]CHAR_INFO Ɏg摜Rs[ COORD size = { SCREEN_WIDTH , SCREEN_HEIGHT }; //!<މ摜̃TCY COORD StartPoint = { 0,0 }; //!<3Dɂ郏[hŴ悤Ȃ SMALL_RECT ScreenData = { 0,0,SCREEN_WIDTH - 1,SCREEN_HEIGHT };//!<މ摜̏㉺AE }tagSCREEN_INFO; //!@brief BMP摜̓ǂݍ //!@param name ǂݍ݂摜AhX݂œ //!@param imageifo 摜̏\̂̃AhX void BitmapRead(const char* name, tagIMAGE_INFO* imageinfo); //!@brief BMP摜pbgɃZbg֐ //!@param pos 摜`ʂ钆Sʒuw //!@param imageinfo `ʂ摜 void BitmapSet(COORD pos, tagIMAGE_INFO* imageinfo); //!@brief F̕ފ֐ //!@param blue ‚̏ //!@param green ΂̏ //!@param red Ԃ̏ //!@details ōł߂16FɕނĂ int Define16Color(int blue,int green,int red); //!@brief pbg֐ void ResetScreen(void); //!@brief pbgR\[ɓ]֐ void Draw();
C
#include<stdio.h> void greatestNum(int*,int*,int*,int*); void main(){ int num1,num2,num3,g; printf("\nEnter the 3 no.s\n"); scanf("%d %d %d",&num1,&num2,&num3); greatestNum(&num1,&num2,&num3,&g); printf("\nGreatest number is: %d\n",g); } void greatestNum(int*n1, int*n2, int*n3, int*g){ *g = *n1>*n2?(*n1>*n3?*n1:*n3):(*n2>*n3?*n2:*n3); }
C
#include "../tl_common.h" #include "../mcu/clock.h" #include "i2c.h" #ifndef PIN_I2C_CN #define PIN_I2C_CN GPIO_CN #endif #ifndef PIN_I2C_SCL #define PIN_I2C_SCL GPIO_CK #endif #ifndef PIN_I2C_SDA #define PIN_I2C_SDA GPIO_DI #endif static inline void i2c_wait(void){ } void i2c_long_wait(void){ CLOCK_DLY_600NS; } // Pulling the line to ground is considered a logical zero while letting the line float is a logical one. http://en.wikipedia.org/wiki/I%C2%B2C static inline void i2c_scl_out(int v){ gpio_set_output_en(PIN_I2C_SCL, (!v)); } static inline int i2c_scl_in(void){ return gpio_read(PIN_I2C_SCL); } // Pulling the line to ground is considered a logical zero while letting the line float is a logical one. http://en.wikipedia.org/wiki/I%C2%B2C static inline void i2c_sda_out(int v){ gpio_set_output_en(PIN_I2C_SDA, (!v)); } static inline int i2c_sda_in(void){ return gpio_read(PIN_I2C_SDA); } static inline void i2c_scl_init(void){ gpio_set_func(PIN_I2C_SCL, AS_GPIO); } static inline void i2c_sda_init(void){ gpio_set_func(PIN_I2C_SDA, AS_GPIO); gpio_set_input_en(PIN_I2C_SDA, 1); } static inline void i2c_scl_idle(void){ gpio_set_output_en(PIN_I2C_SCL, 0); gpio_write(PIN_I2C_SCL, 0); } static inline void i2c_sda_idle(void){ gpio_set_output_en(PIN_I2C_SDA, 0); gpio_write(PIN_I2C_SDA, 0); } void i2c_init(){ gpio_write(PIN_I2C_CN, 1); gpio_write(PIN_I2C_SDA, 1); } /* \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\ void i2c_start(void) \\ Sets clock high, then data high. This will do a stop if data was low. \\ Then sets data low, which should be a start condition. \\ After executing, data is left low, while clock is left high \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ */ void i2c_start(void) { i2c_scl_init(); i2c_sda_init(); i2c_sda_idle(); i2c_scl_idle(); i2c_sda_out(1); //sda: 1 i2c_scl_out(1); //scl: 1 i2c_sda_out(0); //sda: 0 i2c_wait(); } /* \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\ void i2c_stop(void) \\ puts data low, then clock low, \\ then clock high, then data high. \\ This should cause a stop, which \\ should idle the bus, I.E. both clk and data are high. \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ */ void i2c_stop(void) { i2c_sda_out(0); i2c_wait(); i2c_scl_out(0); i2c_wait(); i2c_scl_out(1); i2c_wait(); i2c_sda_out(1); } static void i2c_wirte_bit (int bit) { i2c_scl_out(0); i2c_sda_out(bit); i2c_long_wait(); i2c_scl_out(1); } // Read a bit from I2C bus static int i2c_read_bit(void) { i2c_wirte_bit(1); return i2c_sda_in(); } int i2c_write_byte(u8 dat){ int i = 0x80; while(i){ i2c_wirte_bit((dat & i)); i = i >> 1; } return i2c_read_bit(); } u8 i2c_read_byte(int last){ u8 dat = 0; foreach(i, 8){ i2c_wirte_bit(1); if(i2c_sda_in()){ dat = (dat << 1) | 0x01; }else{ dat = dat << 1; } } i2c_wirte_bit(last); return dat; } void i2c_write(u8 id, u8 addr, u8 dat) { i2c_start(); i2c_write_byte(id); i2c_write_byte(addr); i2c_write_byte(dat); i2c_stop(); } u8 i2c_read(u8 id, u8 addr) { u8 dat; i2c_burst_read (id, addr, &dat, 1); return dat; } void i2c_burst_read(u8 id, u8 addr,u8 *p,u8 n) { i2c_start(); i2c_write_byte (id); i2c_write_byte (addr); i2c_sda_out(1); i2c_scl_out(0); i2c_long_wait(); i2c_scl_out(1); i2c_sda_out(0); i2c_write_byte (id | 1); for (int k = 0; k < n; ++k) { *p++ = i2c_read_byte( k == (n-1) ); } i2c_stop(); }
C
#include <stdio.h> #include <string.h> #define MaxLine 1024 int rmnewline(char line[MaxLine]){ int i; while(line[i] != '\n') i++; line[i] = '\0'; return i; } int main(){ int i, j, Cnt; char Word[1000][MaxLine], *ptr; while(scanf("%s", Word[Cnt])!=EOF){ Cnt++; } for(i=0; i<Cnt; i++){ ptr = Word[i]; for(j=0; j<Cnt; j++){ if(strcmp(Word[j], ptr) == 0) ++numbers } } /* for(j=0; j<i; j++) printf("%s\n", Word[j]); */ }
C
/* * $Id$ */ /************************************************************************ * * * Copyright (C) 2003 * * Internet2 * * All Rights Reserved * * * ************************************************************************/ /* * File: arithm64.c * * Author: Jeff W. Boote * Internet2 * * Date: Tue Sep 16 14:25:16 MDT 2003 * * Description: * Arithmatic and conversion functions for the BWLNum64 * type. * * BWLNum64 is interpreted as 32bits of "seconds" and 32bits of * "fractional seconds". * The byte ordering is defined by the hardware for this value. 4 MSBytes are * seconds, 4 LSBytes are fractional. Each set of 4 Bytes is pulled out * via shifts/masks as a 32bit unsigned int when needed independently. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <stdlib.h> #include <stdio.h> #include <assert.h> #include <string.h> #include <bwlib/bwlib.h> #define MASK32(x) ((x) & 0xFFFFFFFFUL) #define BILLION 1000000000UL #define MILLION 1000000UL #define EXP2POW32 0x100000000ULL /************************************************************************ * * * Arithmetic functions * * * ************************************************************************/ /* * Function: BWLNum64Mult * * Description: * Multiplication. Allows overflow. * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ BWLNum64 BWLNum64Mult( BWLNum64 x, BWLNum64 y ) { uint64_t xlo, xhi, ylo, yhi; xlo = MASK32(x); xhi = MASK32(x>>32); ylo = MASK32(y); yhi = MASK32(y>>32); return ((xlo*ylo)>>32) + (xhi*ylo) + (xlo*yhi) + ((xhi*yhi)<<32); } /************************************************************************ * * * Conversion functions * * * ************************************************************************/ /* * Function: BWLULongToNum64 * * Description: * Convert an unsigned 32-bit integer into a BWLNum64 struct.. * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ BWLNum64 BWLULongToNum64(uint32_t a) { return ((uint64_t)a << 32); } /* * Function: BWLI2numTToNum64 * * Description: * Convert an unsigned 64-bit integer into a BWLNum64 struct.. * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ BWLNum64 BWLI2numTToNum64(I2numT a) { return (a << 32); } /* * Function: BWLNum64toTimespec * * Description: * Convert a time value in BWLNum64 representation to timespec * representation. These are "relative" time values. (Not absolutes - i.e. * they are not relative to some "epoch".) BWLNum64 values are * unsigned 64 integral types with the MS (Most Significant) 32 bits * representing seconds, and the LS (Least Significant) 32 bits * representing fractional seconds (at a resolution of 32 bits). * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ void BWLNum64ToTimespec( struct timespec *to, BWLNum64 from ) { /* * MS 32 bits represent seconds */ to->tv_sec = (long)MASK32(from >> 32); /* * LS 32 bits represent fractional seconds, normalize them to nsecs: * frac/2^32 == nano/(10^9), so * nano = frac * 10^9 / 2^32 */ to->tv_nsec = (long)MASK32((MASK32(from)*BILLION) >> 32); while(to->tv_nsec >= (long)BILLION){ to->tv_sec++; to->tv_nsec -= BILLION; } } /* * Function: BWLTimespecToNum64 * * Description: * * Convert a time value in timespec representation to an BWLNum64 * representation. These are "relative" time values. (Not absolutes - i.e. * they are not relative to some "epoch".) BWLNum64 values are * unsigned 64 integral types with the Most Significant 32 of those * 64 bits representing seconds. The Least Significant 32 bits * represent fractional seconds at a resolution of 32 bits. * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ void BWLTimespecToNum64( BWLNum64 *to, struct timespec *from ) { uint32_t sec = from->tv_sec; uint32_t nsec = from->tv_nsec; *to = 0; /* * Ensure nsec's is only fractional. */ while(nsec >= BILLION){ sec++; nsec -= BILLION; } /* * Place seconds in MS 32 bits. */ *to = (uint64_t)MASK32(sec) << 32; /* * Normalize nsecs to 32bit fraction, then set that to LS 32 bits. */ *to |= MASK32(((uint64_t)nsec << 32)/BILLION); return; } /* * Function: BWLNum64toTimeval * * Description: * Convert a time value in BWLNum64 representation to timeval * representation. These are "relative" time values. (Not absolutes - i.e. * they are not relative to some "epoch".) BWLNum64 values are * unsigned 64 integral types with the MS (Most Significant) 32 bits * representing seconds, and the LS (Least Significant) 32 bits * representing fractional seconds (at a resolution of 32 bits). * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ void BWLNum64ToTimeval( struct timeval *to, BWLNum64 from ) { /* * MS 32 bits represent seconds */ to->tv_sec = (long)MASK32(from >> 32); /* * LS 32 bits represent fractional seconds, normalize them to usecs: * frac/2^32 == micro/(10^6), so * nano = frac * 10^6 / 2^32 */ to->tv_usec = (long)MASK32((MASK32(from)*MILLION) >> 32); while(to->tv_usec >= (long)MILLION){ to->tv_sec++; to->tv_usec -= MILLION; } } /* * Function: BWLTimevalToNum64 * * Description: * * Convert a time value in timeval representation to an BWLNum64 * representation. These are "relative" time values. (Not absolutes - i.e. * they are not relative to some "epoch".) BWLNum64 values are * unsigned 64 integral types with the Most Significant 32 of those * 64 bits representing seconds. The Least Significant 32 bits * represent fractional seconds at a resolution of 32 bits. * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ void BWLTimevalToNum64( BWLNum64 *to, struct timeval *from ) { uint32_t sec = from->tv_sec; uint32_t usec = from->tv_usec; *to = 0; /* * Ensure usec's is only fractional. */ while(usec >= MILLION){ sec++; usec -= MILLION; } /* * Place seconds in MS 32 bits. */ *to = (uint64_t)MASK32(sec) << 32; /* * Normalize usecs to 32bit fraction, then set that to LS 32 bits. */ *to |= MASK32(((uint64_t)usec << 32)/MILLION); return; } /* * Function: BWLNum64toDouble * * Description: * Convert an BWLNum64 time value to a double representation. * The double will contain the number of seconds with the fractional * portion of the BWLNum64 mapping to the portion of the double * represented after the radix point. This will obviously loose * some precision after the radix point, however - larger values * will be representable in double than an BWLNum64. * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ double BWLNum64ToDouble( BWLNum64 from ) { return (double)from / EXP2POW32; } /* * Function: BWLDoubleToNum64 * * Description: * Convert a double value to an BWLNum64 representation. * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ BWLNum64 BWLDoubleToNum64( double from ) { if(from < 0){ return 0; } return (BWLNum64)(from * EXP2POW32); } /* * Function: BWLUsecToNum64 * * Description: * Convert an unsigned 32bit number representing some number of * microseconds to an BWLNum64 representation. * * In Args: * * Out Args: * * Scope: * Returns: * Side Effect: */ BWLNum64 BWLUsecToNum64(uint32_t usec) { return ((uint64_t)usec << 32)/MILLION; }
C
#include <stdio.h> void troca(int *val1, int *val2); int main(void) { int val1, val2; printf("Coloque dois valores:\n> "); scanf("%d %d", &val1, &val2); troca(&val1, &val2); printf("%d %d\n", val1, val2); } void troca(int *val1, int *val2) { int aux; aux = *val1; *val1 = *val2; *val2 = aux; }
C
#include "libc/stdio.h" #include <unistd.h> // for pipe, close, exec #include <stdlib.h> // for free() #include <errno.h> #include "libc/cdefs.h" static void do_child(int cfd, int rw, const char *cmd) __NORETURN; static void do_child(int cfd, int rw, const char *cmd) { FILE *S; int sfd; // stdin/stdout if (rw == SF_RD) sfd = STDOUT_FILENO; else sfd = STDIN_FILENO; // redirect the child fd to stdin or stdout if (cfd != sfd) { dup2(cfd, sfd); // FIXME: ignore any error ??? close(cfd); } // POSIX requirement for_each_file(S) { if (S->flags & SF_ISPIPE) close(S->fd); } execl("/bin/sh", "sh", "-c", cmd, NULL); _exit(127); } FILE *popen(const char *cmd, const char *mode) { int pfd, cfd; int fds[2]; int rw; pid_t pid; FILE *S; if ((mode[0] != 'r' && mode[0] != 'w') || mode[0] == '\0' || mode[1] != '\0') { errno = EINVAL; return NULL; } S = __stdio_new(); if (__unlikely(!S)) return S; if (pipe(fds) < 0) goto error; if (mode[0] == 'r') { pfd = fds[0]; cfd = fds[1]; rw = SF_RD; } else { pfd = fds[1]; cfd = fds[0]; rw = SF_WR; } pid = fork(); if (__unlikely(pid == -1)) { close(pfd); close(cfd); goto error; } else if (pid == 0) // child { close(pfd); do_child(cfd, rw, cmd); // never reached } else // pid > 0: parent { close(cfd); S->fd = pfd; S->flags = SF_BUFBLCK | SF_ISPIPE | rw; insert_entry(S); return S; } error: free(S->base); free(S); return NULL; }
C
#include <stdio.h> #include <stdlib.h> int n; int b[150]={0}; char a[600]; long long sum=0; void print() { int i; sum++; for(i=1;i<=n;++i) { printf("%c",a[i]); } printf("\n"); } void search(int i) { int j; for( j='a';j<='z';++j) { if(b[j]!=0) { a[i]=j; b[j]--; if(i==n) { print(); } else { search(i+1); } b[j]++; } } } int main() { scanf("%d\n",&n); char c; int i; for( i=1;i<=n;++i) { scanf("%c",&c); b[c]++; } scanf("%c",&c); search(1); printf("%lld",sum); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* array_utils.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: scornaz <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/04/01 15:48:12 by scornaz #+# #+# */ /* Updated: 2018/04/02 14:11:19 by scornaz ### ########.fr */ /* */ /* ************************************************************************** */ #include "lemmi.h" void p(void *data, t_array *array) { printf(" %s", (*(t_node**)data)->name); } void print_node(void *n, t_array *array) { t_node *node; node = n; printf("name : %s\npos: %d et %d\n", node->name, node->y, node->x); printf("solutions: %d et %d\n", node->sol_from_start, node->sol_from_end); printf("connexions :"); if (node->connexions_ptr) array_for_each(node->connexions_ptr, p); printf("\n\\\\\\\n"); fflush(stdout); } int p_strequ(void *a, void *b) { return (ft_strequ(((t_node*)a)->name, b)); } t_array *hydrate(t_array *list, char **connexions, int salles) { t_node *node; t_node sol; char **names; int i; int j; i = -1; while (++i < salles) { node = ((t_node*)(list->mem) + i); node->connexions = array_new(sizeof(char), 4); j = 0; while (connexions[j]) { names = ft_strsplit(connexions[j], '-'); if (ft_strequ(names[0], node->name)) { array_add(node->connexions, names[1], ft_strlen(names[1])); array_add(node->connexions, "|", 1); } ++j; ft_free_strsplit(names); } } return (list); } void free_f(t_array *array) { t_node *node; int i; i = 0; node = ((t_node*)array->mem); while (i < array->cursor) { free(node[i].name); array_free(node[i].connexions); array_free(node[i].connexions_ptr); ++i; } free(node); }
C
// ============================================================================= // <integer/convert/hexadecimal/deserialize/implicit/i32.c> // // 32-bit+ hexadecimal null-terminated string to integer conversion template. // // Copyright Kristian Garnét. // ----------------------------------------------------------------------------- #include "intro.h" // ----------------------------------------------------------------------------- if (true) { #include "intro.c" #if T(VALID) && (!HAVE(INT32) || !HAVE(INT16)) // Vectorization is not available or is not feasible #if T(UNEVEN) int_from_xstr (val, str, str + T_MAXDIG - 1, {c = *str; goto invalid;}); #else int_from_xstr (val, str, str + T_MAXDIG, {c = *str; goto invalid;}); #endif goto outro; #endif // Parse until the alignment is satisfied t_stri_align (4u); // 4 digits #if T(VALID) while (len < T_MAXDIG - 4u) #else while (true) #endif { int_from_xdigi (val, str, 4, 16, {goto skip;}); str += 4u; #if T(VALID) len += 4u; #endif } #if T(VALID) // Remaining 2 digits if (len < T_MAXDIG - 2u) { int_from_xdigi (val, str, 2, 8, {goto skip;}); str += 2u; len += 2u; } // Last digit if (len != T_MAXDIG - 1u) { c = *str; if (unlikely (!chr_is_xdig (c))) goto invalid; val = (val << 4) + chr_xdig_to_int_fast (c); str++; } #endif #include "outro.c" } // ----------------------------------------------------------------------------- #include "outro.h"
C
#include "tlb_hrchy_mng.h" #include "addr.h" #include "addr_mng.h" #include "page_walk.h" #include <stdio.h> #include <stdlib.h> #include <inttypes.h> #include <string.h> #include "error.h" #include <stdbool.h> //================================================================================================================ // define constants for hit and miss #define HIT 1 #define MISS 0 //================================================================================================================ /** * @brief Clean a TLB with type type * * @param type : type of tlb (l1_itlb_entry_t, l1_dtlb_entry_t, l2_tlb_entry_t) * @param tlb : the (generic) pointer to the TLB * @param NB_LINES : the maximum number of lines of the tlb * * it first test the overflow of sizeof(type)*NB_LINE */ #define flush_generic(type, tlb, NB_LINES) \ M_REQUIRE((NB_LINES <= SIZE_MAX/sizeof(type)), ERR_SIZE, "Could not memset : overflow, %c", " "); \ memset(tlb , 0, sizeof(type)*NB_LINES); \ return ERR_NONE; //================================================================================================================ /** * @brief Clean a TLB (invalidate, reset...). This function erases all TLB data. * * Requirements : * @param tlb (generic) pointer to the TLB, must be non null * @param tlb_type an enum to distinguish between different TLBs * @return error code * * */ int tlb_flush(void *tlb, tlb_t tlb_type){ M_REQUIRE_NON_NULL(tlb); // test if the tlb_type is a valid instance of tlb_t M_REQUIRE(L1_ITLB <= tlb_type && tlb_type <= L2_TLB, ERR_BAD_PARAMETER, "%d is not a valid tlb_type \n", tlb_type); // for each tlb type call the generic macro defined before switch (tlb_type) { case L1_ITLB : flush_generic(l1_itlb_entry_t, tlb, L1_ITLB_LINES); break; case L1_DTLB : flush_generic(l1_dtlb_entry_t, tlb, L1_DTLB_LINES); break; case L2_TLB : flush_generic(l2_tlb_entry_t , tlb, L2_TLB_LINES ); break; default : return ERR_BAD_PARAMETER; break; //not needed because of sanity checks but this is left for the compiler } //should not arrive here since each switch case contains a return (see macro expansion) } //==================================================================================== /** * @brief generic macro that checks if a TLB entry exists in the TLB. * * On hit, return HIS (1) and update the physical page number passed as the pointer to the function. * On miss, return MISS (0). * * @param type : type of tlb (l1_itlb_entry_t, l1_dtlb_entry_t, l2_tlb_entry_t) * @param tlb : pointer to the beginning of the tlb * @param vaddr : pointer to virtual address * @param paddr : (modified) pointer to physical address * @param LINES_BITS : the number of bits needed to represent NB_LINES * @param NB_LINES : the maximum number of lines of the tlb * @return HIS or MISS or MISS in case of an error * * the method first computes the 64 bits virtual address in order to extract the tag and the * line where the entry could be found. * * if the entry is valid and the tag is correct => it's a hit and we update paddr else it's a miss * if init_phy_addr fails we return 0 (MISS) */ #define hit_generic(type, tlb, vaddr, paddr, LINES_BITS, NB_LINES) \ uint64_t addr = virt_addr_t_to_virtual_page_number(vaddr); \ uint32_t tag = (addr) >> (LINES_BITS); \ uint8_t line = (addr) % (NB_LINES); \ type entry = ((type*) tlb)[line]; \ if (entry.tag == tag && entry.v == 1) { \ int err = init_phy_addr(paddr, entry.phy_page_num << PAGE_OFFSET, vaddr->page_offset); \ if (err != ERR_NONE) return MISS; \ return HIT; \ } \ else return MISS; //==================================================================================== /** * @brief Check if a TLB entry exists in the TLB. * * On hit, return HIT(1) and update the physical page number passed as the pointer to the function. * On miss, return MISS (0). * * Requirements : * @param vaddr : must be non null * @param paddr : must be non null * @param tlb : must be non null * @param tlb_type : must be a valid instance of tlb_t * @return HIT (1) or MISS (0) */ int tlb_hit( const virt_addr_t * vaddr, phy_addr_t * paddr, const void * tlb, tlb_t tlb_type){ if(vaddr == NULL || paddr == NULL || tlb == NULL)return MISS; // check that tlb_type is a valid instance of tlb_t if (! (L1_ITLB <= tlb_type && tlb_type <= L2_TLB)) return MISS; // for each tlb type call the generic macro defined before switch (tlb_type) { case L1_ITLB : { hit_generic(l1_itlb_entry_t, tlb, vaddr, paddr, L1_ITLB_LINES_BITS, L1_ITLB_LINES);} break; case L1_DTLB : { hit_generic(l1_dtlb_entry_t, tlb, vaddr, paddr, L1_DTLB_LINES_BITS, L1_DTLB_LINES);} break; case L2_TLB : { hit_generic(l2_tlb_entry_t , tlb, vaddr, paddr, L2_TLB_LINES_BITS , L2_TLB_LINES );} break; default : return MISS; break; } // should not arrive here since each switch case contains a return (see macro expansion) } //========================================================================= /** * @brief Insert an entry to a tlb (in a generic fashion) * * @param type : type of tlb (l1_itlb_entry_t, l1_dtlb_entry_t, l2_tlb_entry_t) * @param tlb : pointer to the beginning of the tlb * @param tlb_entry : pointer to the tlb entry to insert * @param line_index : the number of the line to overwrite * @param NB_LINES : the maximum number of lines of the tlb * @param returns ERR_NONE or an error code in case of an error * * it first validate line_index since line_index sould be smaller that NB_LINES * then it casts tlb and indexes it to update it with the new entry (that also need to be casted) */ #define insert_generic(type, tlb, tlb_entry, line_index, NB_LINES) \ M_REQUIRE(line_index < NB_LINES, ERR_BAD_PARAMETER, "%"PRIx32" should be smaller than " #NB_LINES, line_index); \ ((type*)tlb)[line_index] = *((type*)tlb_entry); \ return ERR_NONE; //========================================================================= /** * @brief Insert an entry to a tlb * * Requirements : * @param line_index should be smaller than the maximum number of lines of tlb * @param tlb_entry must be non mull * @param tlb must be non null * @param tlb_type : must be a valid instance of tlb_t * @return error code */ int tlb_insert(uint32_t line_index, const void * tlb_entry, void * tlb,tlb_t tlb_type){ M_REQUIRE_NON_NULL(tlb); M_REQUIRE_NON_NULL(tlb_entry); // check that tlb_type is a valid instance of tlb_t M_REQUIRE(L1_ITLB <= tlb_type && tlb_type <= L2_TLB, ERR_BAD_PARAMETER, "%d is not a valid tlb_type \n", tlb_type); // for each tlb type call the generic macro defined above switch (tlb_type) { case L1_ITLB : insert_generic(l1_itlb_entry_t, tlb, tlb_entry, line_index, L1_ITLB_LINES); break; case L1_DTLB : insert_generic(l1_dtlb_entry_t, tlb, tlb_entry, line_index, L1_DTLB_LINES); break; case L2_TLB : insert_generic(l2_tlb_entry_t , tlb, tlb_entry, line_index, L2_TLB_LINES) ; break; default : return ERR_BAD_PARAMETER; break; } // should not arrive here since each switch case contains a return (see macro expansion) } //========================================================================= /** * @brief Initialize a TLB entry (in a generic fashion) * * @param type : type of tlb (l1_itlb_entry_t, l1_dtlb_entry_t, l2_tlb_entry_t) * @param tlb_entry : pointer to the entry to be initialized * @param LINES_BITS : the number of bits needed to represent the number of lines of the given tlb * @param vaddr : pointer to virtual address to extract the tag * @param paddr : pointer to physical address to extract the physical page number * * it first compute the tag by converting the vaddr to a 64 bits virtual address * then it set phy_page_num = (paddr)->phy_page_num and set the valid bit to 1 * * /!\ it is assumed that virt_addr_t_to_virtual_page_number will not generate any error since * vaddr cannot be null (it should be checked by the caller of the macro), so no need to propagate * the error. This is done because virt_addr_t_to_virtual_page_number returns a value and we cannot * distinguish normal values from errors */ #define init_generic(type, tlb_entry, LINES_BITS, vaddr, paddr) \ type* entry = (type*)(tlb_entry); \ entry->tag = virt_addr_t_to_virtual_page_number(vaddr) >> (LINES_BITS); \ entry->phy_page_num = (paddr)->phy_page_num; \ entry->v = 1; //========================================================================= /** * @brief Initialize a TLB entry * * Requirements : * @param vaddr : must be non null * @param paddr : must be non null * @param tlb_entry : must be non null * @param tlb_type : must be a valid instance of tlb_t * @return error code */ int tlb_entry_init( const virt_addr_t * vaddr, const phy_addr_t * paddr, void * tlb_entry,tlb_t tlb_type){ M_REQUIRE_NON_NULL(vaddr); M_REQUIRE_NON_NULL(paddr); M_REQUIRE_NON_NULL(tlb_entry); // check that tlb_type is a valid instance of tlb_t M_REQUIRE(L1_ITLB <= tlb_type && tlb_type <= L2_TLB, ERR_BAD_PARAMETER, "%d is not a valid tlb_type \n", tlb_type); // for each tlb type call the generic macro defined above switch (tlb_type){ case L1_ITLB : { init_generic(l1_itlb_entry_t, tlb_entry, L1_ITLB_LINES_BITS, vaddr, paddr);} break; case L1_DTLB : { init_generic(l1_dtlb_entry_t, tlb_entry, L1_DTLB_LINES_BITS, vaddr, paddr);} break; case L2_TLB : { init_generic(l2_tlb_entry_t , tlb_entry, L2_TLB_LINES_BITS , vaddr, paddr);} break; default : return ERR_BAD_PARAMETER; break; } // here the return is needed since the macro does not return anything return ERR_NONE; } /** * @brief Invalides a tlb entry, only made to be used inside of the method search, never else, hence it has previouslyValid and previousTag not as arguments, only used for genericity purposes * * @param tlb : tlb where we must check if we need to invalidate an entry * @param vaddr : address that gives us the line of the entry that we must invalidate * @param TLB_LINES : Number of lines in the given tlb * * It first computes the index at which we must try to invalidate the entry using the vaddr and TLB_LINES and then applies the algorithm to invalidate as given in the pdf */ #define invalidate(tlb,vaddr,TLB_LINES) \ uint8_t index = virt_addr_t_to_virtual_page_number(vaddr) % TLB_LINES;\ if((previouslyValid && tlb[index].v && (tlb[index].tag >> 2== previousTag)) || needEviction) tlb[index].v = 0;\ /** * @brief Creates and inserts a tlb entry into the tlb given as argument * * @param entry_type : type of the entry that needs to be inserted * @param tlb : the tlb in which we insert the entry * @param TLB_TYPE : the type of the tlb in which we add the entry * @param tlb_lines : either L1_ITLB_LINES, L1_DTLB_LINES or L2_TLB_LINES, the number of lines in the tlb * @param vaddr : pointer to virtual address to extract the tag * @param paddr : pointer to physical address to extract the physical page number * * It first creates an entry, initializes it, then computes the index in which we need to put it and finally inserts it */ #define create_and_insert_entry(entry_type, tlb, TLB_TYPE, tlb_lines, vaddr, paddr) \ entry_type entry;\ int err;\ if((err = tlb_entry_init(vaddr, paddr, &entry,TLB_TYPE)) != ERR_NONE) return err; \ uint8_t line = virt_addr_t_to_virtual_page_number(vaddr) % tlb_lines;\ if((err = tlb_insert(line, &entry, tlb, TLB_TYPE)) != ERR_NONE) return err; //========================================================================= /** * @brief Ask TLB for the translation. * * @param mem_space pointer to the memory space * @param vaddr pointer to virtual address * @param paddr (modified) pointer to physical address (returned from TLB) * @param access to distinguish between fetching instructions and reading/writing data * @param l1_itlb pointer to the beginning of L1 ITLB * @param l1_dtlb pointer to the beginning of L1 DTLB * @param l2_tlb pointer to the beginning of L2 TLB * @param hit_or_miss (modified) hit (1) or miss (0) * @return error code */ int tlb_search( const void * mem_space,const virt_addr_t * vaddr, phy_addr_t * paddr, mem_access_t access, l1_itlb_entry_t * l1_itlb, l1_dtlb_entry_t * l1_dtlb, l2_tlb_entry_t * l2_tlb, int* hit_or_miss){ M_REQUIRE_NON_NULL(mem_space); M_REQUIRE_NON_NULL(vaddr); M_REQUIRE_NON_NULL(paddr); M_REQUIRE_NON_NULL(l1_itlb); M_REQUIRE_NON_NULL(l1_dtlb); M_REQUIRE_NON_NULL(l2_tlb); M_REQUIRE_NON_NULL(hit_or_miss); M_REQUIRE(access == INSTRUCTION || access == DATA, ERR_BAD_PARAMETER, "access is not a valid instance of mem_access_t %c", ' '); int err = ERR_NONE; // err used to propagate errors *hit_or_miss = (access == INSTRUCTION)? tlb_hit(vaddr, paddr, l1_itlb, L1_ITLB):tlb_hit(vaddr, paddr, l1_dtlb, L1_DTLB); if(*hit_or_miss == HIT) return ERR_NONE; //if found in lvl 1, return *hit_or_miss = tlb_hit(vaddr, paddr, l2_tlb, L2_TLB);//else search for it in lvl2 uint8_t previouslyValid = 0;//previouslyValid and tag exist to check whether to invalidate the lvl1 tlb entry or not uint32_t previousTag = 0; // correcteur: unwanted eviction on L2 hit bool needEviction = true; if(!*hit_or_miss){ //do page_walk if not found M_REQUIRE(page_walk(mem_space, vaddr, paddr) == ERR_NONE, ERR_MEM, "Couldnt find the paddr corresponding to this vaddr", ""); //page walk to get the right paddr since we havent found //here we would to use the macro we created to insert an entry but there is no point since we need to get the value previouslValid and previousTag anyways //assume that virt_addr_t_to_virtual_page_number does not return any error since vaddr is not null uint8_t line = virt_addr_t_to_virtual_page_number(vaddr) % L2_TLB_LINES; //get the right line in the lvl2 to create the entry l2_tlb_entry_t entry; if ((err = tlb_entry_init(vaddr, paddr, &entry, L2_TLB))!= ERR_NONE) {return err;} //init the lvl2 entry and propagate error if needed //check if there was a previously valid entry at this part previouslyValid = l2_tlb[line].v; //init previouslyValid and tag previousTag = (l2_tlb[line].tag); needEviction = false; //boolean that tells us whether we also need to evict if ((err = tlb_insert(line, &entry, l2_tlb, L2_TLB)) != ERR_NONE) {return err;}//inserts the new entry in the lvl2 tlb propagate error if needed } if(access == INSTRUCTION){ //creates and inserts the entry in this tlb create_and_insert_entry(l1_itlb_entry_t, l1_itlb, L1_ITLB, L1_ITLB_LINES, vaddr,paddr); //invalidate entry in the other tlb invalidate(l1_dtlb, vaddr, L1_DTLB_LINES); } else{ //creates and inserts the entry in this tlb create_and_insert_entry(l1_dtlb_entry_t, l1_dtlb, L1_DTLB, L1_DTLB_LINES, vaddr,paddr); //invalidate entry in the other tlb invalidate(l1_itlb, vaddr, L1_ITLB_LINES); } return ERR_NONE; }
C
#include <stdio.h> #include <stdlib.h> int main() { float n1, n2, n3, media; printf("Insira a primeira nota: "); scanf("%f", &n1); getchar(); printf("Insira a segunda nota: "); scanf("%f", &n2); getchar(); printf("Insira a terceira nota: "); scanf("%f", &n3); getchar(); media=(n1+n2+n3)/3; printf("Sua media foi: %.2f\n", media); if(media>=5) printf("Aprovado!\n\n"); else if (media<5) printf("Reprovado!\n\n"); system ("PAUSE"); return 42; }
C
/* Strukture */ #include <stdio.h> typedef struct { float x; float y; } tocka; typedef double stanje; int main(int argc, char **argv) { tocka a; tocka *kaz; stanje s = 4.3; kaz = &a; kaz->x=3.2; a.y = -1.1; printf("x: %g y: %g\n",kaz->y,a.x); return 0; }
C
#include<iostream> using namespace std; int main() { int t; unsigned long long int i,n; cin>>t; for(int j=1;j<=t;j++) { cin>>n; if(n%2==0) { for(i=n/2;i>=1;i=i/2) { if((n%i==0)&&(i%2!=0)) { cout<<"Case "<<j<<": "<<i<<endl; break; } } } else cout<<"Case "<<j<<": "<<n<<endl; } }
C
/* * I DONT KNOW THE ORIGIN OF THIS SOURCE CODE FILE, * THUS THE LICENSE AND AUTHOR ??? * * Basile Fourcade: I've made some modifications in it. * * */ #ifndef __BUTTON_H__ #define __BUTTON_H__ // Button #define NB_BUTTONS 1 #define LED_BUTTON_MODE_PIN 4 // Button timing variables #define DEBOUNCE 10 // ms debounce period to prevent flickering when pressing or releasing the button #define DCGAP 200 // max ms between clicks for a double click event #define HOLDTIME 1500 // ms hold period: how long to wait for press+hold event #define LONGHOLDTIME 4000 // ms long hold period: how long to wait for press+hold event // Other button variables boolean buttonVal[NB_BUTTONS] = { HIGH }; // value read from button boolean buttonLast[NB_BUTTONS] = { HIGH }; // buffered value of the button's previous state boolean DCwaiting[NB_BUTTONS] = { false }; // whether we're waiting for a double click (down) boolean DConUp[NB_BUTTONS] = { false }; // whether to register a double click on next release, or whether to wait and click boolean singleOK[NB_BUTTONS] = { true }; // whether it's OK to do a single click long downTime[NB_BUTTONS] = { -1 }; // time the button was pressed down long upTime[NB_BUTTONS] = { -1 }; // time the button was released boolean ignoreUp[NB_BUTTONS] = { false }; // whether to ignore the button release because the click+hold was triggered boolean waitForUp[NB_BUTTONS] = { false }; // when held, whether to wait for the up event boolean holdEventPast[NB_BUTTONS] = { false }; // whether or not the hold event happened already boolean longHoldEventPast[NB_BUTTONS] = { false }; // whether or not the long hold event happened already /* Run checkButton() to retrieve a button event: Click Double-Click Hold Long Hold */ enum button_event_t { NO_EVENT = 0, CLICK = 1, DOUBLE_CLICK = 2, HOLD = 3, LONG_HOLD = 4, }; button_event_t checkButton(uint8_t pin) { button_event_t event = NO_EVENT; uint8_t idx = 0; // Read the state of the button buttonVal[idx] = digitalRead(pin); // Button pressed down if (buttonVal[idx] == LOW && buttonLast[idx] == HIGH && (millis() - upTime[idx]) > DEBOUNCE) { downTime[idx] = millis(); ignoreUp[idx] = false; waitForUp[idx] = false; singleOK[idx] = true; holdEventPast[idx] = false; longHoldEventPast[idx] = false; if ((millis() - upTime[idx]) < DCGAP && DConUp[idx] == false && DCwaiting[idx] == true) DConUp[idx] = true; else DConUp[idx] = false; DCwaiting[idx] = false; } // Button released else if (buttonVal[idx] == HIGH&& buttonLast[idx] == LOW && (millis() - downTime[idx]) > DEBOUNCE) { if (not ignoreUp[idx]) { upTime[idx] = millis(); if (DConUp[idx] == false) { DCwaiting[idx] = true; } else { event = DOUBLE_CLICK; DConUp[idx] = false; DCwaiting[idx] = false; singleOK[idx] = false; } } } // Test for normal click event: DCGAP expired if (buttonVal[idx] == HIGH && (millis() - upTime[idx]) >= DCGAP && DCwaiting[idx] == true && DConUp[idx] == false && singleOK[idx] == true) { event = CLICK; DCwaiting[idx] = false; } // Test for hold if ((buttonVal[idx] == LOW) && (millis() - downTime[idx]) >= HOLDTIME) { // Trigger "normal" hold if (not holdEventPast[idx]) { event = HOLD; waitForUp[idx] = true; ignoreUp[idx] = true; DConUp[idx] = false; DCwaiting[idx] = false; //downTime = millis(); holdEventPast[idx] = true; } // Trigger "long" hold if ((millis() - downTime[idx]) >= LONGHOLDTIME) { if (not longHoldEventPast[idx]) { event = LONG_HOLD; longHoldEventPast[idx] = true; } } } buttonLast[idx] = buttonVal[idx]; return event; } /* Return CLICK if button is pressed */ button_event_t checkButtonStatus(uint8_t pin) { button_event_t event = NO_EVENT; uint8_t idx = 0; // Read the state of the button buttonVal[idx] = digitalRead(pin); /* Button is low, notify*/ if (buttonVal[idx] == LOW) { event = CLICK; } return event; } void initButtonState(void) { uint8_t idx = 0; /* Reset all button variables */ buttonVal[idx] = HIGH; buttonLast[idx] = HIGH; DCwaiting[idx] = false; DConUp[idx] = false; singleOK[idx] = true; downTime[idx] = -1; upTime[idx] = -1; ignoreUp[idx] = false; waitForUp[idx] = false; holdEventPast[idx] = false; longHoldEventPast[idx] = false; } #endif
C
#include<stdio.h> #include<string.h> int bigMOD(char *a, int b){ int len = strlen(a); int mod = (a[0]-'0')%b; int i=1; for(;i<len;i++){ mod = (mod*10+(a[i]-'0'))%b; } return mod; } int getGCD(int a, int b){ while (b != 0) { int t = b; b = a % b; a = t; } return a; } int main(){ int t; scanf("%d",&t); while(t--){ int a; char str[252]; scanf("%d ",&a); scanf ("%[^\n]%*c", str); if(a==0) printf("%s\n",str); else{ int b = bigMOD(str, a); printf("%d\n",getGCD(a,b)); } } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_wstrjoin_leakless.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mapandel <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/04/18 05:09:11 by mapandel #+# #+# */ /* Updated: 2019/11/08 00:26:44 by mapandel ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_wstr.h" /* ** ft_wstrjoin_leakless: wide string join leaklesss ** Creates a wchar_t* from the concatenation ** of a wchar_t* and a wchar_t const* ** Frees up the first source parameter wchar_t* ** NULL behaviors are handled ** Returns this new wide string or NULL if the allocation failed */ wchar_t *ft_wstrjoin_leakless(wchar_t *s1, wchar_t const *s2) { size_t len; wchar_t *result; len = ft_wstrlen_nullcrashless(s1); len += ft_wstrlen_nullcrashless(s2); if (!(result = ft_wstrnew(len))) return (NULL); result = ft_wstrcpy_nullcrashless(result, s1); result = ft_wstrcat_nullcrashless(result, s2); ft_wstrdel(&s1); return (result); }
C
#include <stdio.h> int n; int in[8001]; //has n-1 int out[8001]; // int cmp(const void *a,const void *b){ return *(int*)a-*(int*)b; } int main(){ int i,j; scanf("%d",&n); for(i=0;i<n-1;i++){ scanf("%d",&in[i]); } for(i=0;i<n;i++) out[i]=i+1; // for(i=0;i<n;i++) printf("out %d\n",out[i]); for(i=n-2;i>=0;i--){ int t=in[i]; // printf("t is %d\n",t); // for(j=0;j<n;j++) printf("out %d\n",out[j]); //qsort(out,i+2,sizeof(int),cmp); // for(j=0;j<n;j++) printf("out %d\n",out[j]); // printf("gonna chang %d %d\n",out[i+1],out[t]); if(out[i+1]==out[t]) continue; out[i+1]=out[t]^out[i+1]; out[t]=out[t]^out[i+1]; out[i+1]=out[t]^out[i+1]; int tem=out[t]; for(j=t;j<=i;j++){ out[j]=out[j+1]; } out[i]=tem; // printf("out i+1 is %d,out t is %d\n",out[i+1],out[t]); } for(i=0;i<n;i++) printf("%d\n",out[i]); return 0; }
C
#include <stdio.h> int main() { int a,b,N,d; scanf("%d",&a); while(a--) { scanf("%d",&N); b=0; while(N--) { scanf("%d",&d); b+=d;} printf("%d\n\n",b); } scanf("%d",&N); b=0; while(N--) { scanf("%d",&d); b+=d;} printf("%d\n",b); }
C
// demonstrates passing floating point arguments, // returning a floating point value, // and doing a calculation using the FPU register stack #pragma GCC diagnostic ignored "-Wunused-but-set-variable" int main () { double f; double w = 213.0; double x = 43.0; double y = 20.0; double z = 1.2; f = 3.0 * (w + x) / (y * z); return 0; }
C
#include "c_hmac_md5.h" #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <openssl/md5.h> #include <openssl/sha.h> #include <openssl/hmac.h> #include <openssl/opensslv.h> #include "common.h" void crypto_hmac_md5(uint8_t *input, uint32_t inputLen, uint8_t *output) { uint8_t hmacMd5Digest[MD5_DIGEST_LENGTH]; unsigned int mdLen; // "OpenSSL 1.1.0-pre1-fips (alpha) 10 Dec 2015" #if (OPENSSL_VERSION_NUMBER >= 0x10100001L) HMAC_CTX *ctx; ctx = HMAC_CTX_new(); HMAC_Init_ex(ctx, input, inputLen, EVP_md5(), NULL); HMAC_Update(ctx, input, inputLen); HMAC_Final(ctx, hmacMd5Digest, &mdLen); HMAC_CTX_free(ctx); #else HMAC_CTX ctx; HMAC_CTX_init(&ctx); HMAC_Init_ex(&ctx, input, inputLen, EVP_md5(), NULL); HMAC_Update(&ctx, input, inputLen); HMAC_Final(&ctx, hmacMd5Digest, &mdLen); HMAC_CTX_cleanup(&ctx); #endif uint8_t sha256Digest[SHA256_DIGEST_LENGTH]; SHA256_CTX sha256_ctx; SHA256_Init(&sha256_ctx); SHA256_Update(&sha256_ctx, hmacMd5Digest, MD5_DIGEST_LENGTH); SHA256_Final(sha256Digest, &sha256_ctx); memcpy(output, sha256Digest, OUTPUT_LEN*sizeof(uint8_t)); }
C
/* $ cc -Og -g -fsanitize=address,undefined test.c * On x86-64, add -march=x86-64-v2 to test hardware implementation. * This is free and unencumbered software released into the public domain. */ #include "crc32.h" #include "crc32c.h" #include "adler32.h" #include "crc16x25.h" #include <stdio.h> #define COUNTOF(a) (int)(sizeof(a) / sizeof(0[a])) static const unsigned char test_input[] = "The quick brown fox jumps over the lazy dog"; static const unsigned long test_crc32[] = { 0x00000000, 0xbe047a60, 0xdc6763c5, 0x04082b06, 0x000b625b, 0x09b92d39, 0xad615b1b, 0x6ca49ec6, 0x74d21c74, 0x5f7e3064, 0xa3ec1434, 0x50a9f758, 0x09e98fac, 0xd0669508, 0x1268e5b5, 0xc3118c34, 0xc81b2a7c, 0x2fa80ddd, 0xf7429520, 0xb74574de, 0x88b075e2, 0x31e954ea, 0xb283880c, 0xe8053dcb, 0x8e5980b4, 0xd78ce11e, 0x13b47ec7, 0x0a1c7029, 0x29dcbf98, 0x1127bd93, 0x051e1ade, 0x88022e8c, 0x61ec978d, 0x020315ed, 0x3163e78a, 0xe430c69c, 0x6f5b2d57, 0x1dd72139, 0x3dca2886, 0xff3dca28, 0xdc265a75, 0xb86ee925, 0x44b329ea, }; static const unsigned long test_crc32c[] = { 0x00000000, 0xc4c21e9d, 0x9426ea26, 0x00c29bf3, 0x92fe8395, 0x764592d7, 0x117bd392, 0x388beccc, 0xae1d513f, 0xc46c03cc, 0xfcca5898, 0xca0dde44, 0x44f5f0d6, 0x989e0fa4, 0x9266df01, 0x6d3a9ac8, 0x3bf9991e, 0xa907a60a, 0x06e3d389, 0x537e5cf4, 0x46675bb9, 0x92b82655, 0x725265a9, 0x5618b0ef, 0x9e908bd2, 0x02c3f57f, 0x5d497653, 0x2f809c46, 0x62b19a7c, 0x3af3fe68, 0x29fb4ff8, 0x0b5e117a, 0xfe0eb267, 0x0c9061c7, 0x11010661, 0xe17ccce8, 0x17f083fa, 0x594bf4fe, 0x1748b4c2, 0x79f6c217, 0xb62d88c9, 0x4fa887ac, 0x82ef2ee6, }; static const unsigned long test_adler32[] = { 0x00000001, 0x00550055, 0x011200bd, 0x02340122, 0x03760142, 0x052901b3, 0x07510228, 0x09e20291, 0x0cd602f4, 0x1035035f, 0x13b4037f, 0x179503e1, 0x1be80453, 0x20aa04c2, 0x25e30539, 0x2b8a05a7, 0x315105c7, 0x377e062d, 0x3e1a069c, 0x452e0714, 0x4c620734, 0x5400079e, 0x5c130813, 0x64930880, 0x6d8308f0, 0x76e60963, 0x80690983, 0x8a5b09f2, 0x94c30a68, 0x9f900acd, 0xaacf0b3f, 0xb62e0b5f, 0xc2010bd3, 0xce3c0c3b, 0xdadc0ca0, 0xe79c0cc0, 0xf4c80d2c, 0x02640d8d, 0x106b0e07, 0x1eeb0e80, 0x2d8b0ea0, 0x3c8f0f04, 0x4c020f73, }; static const unsigned test_crc16x25[] = { 0x0000, 0xe4d9, 0x549e, 0xb970, 0xa244, 0x96f4, 0x656f, 0x952b, 0x3ea1, 0x9910, 0xc162, 0xf0b9, 0x8857, 0x4d3b, 0x785d, 0xf318, 0x4d40, 0xb401, 0x7ab4, 0xfc62, 0x9192, 0x8b2e, 0x1ca5, 0xba20, 0xa247, 0x877d, 0x799f, 0x078e, 0x8bb8, 0xfd9b, 0x8a4a, 0x3cae, 0x8993, 0xb9ad, 0xba85, 0x0265, 0x6dbb, 0x89c2, 0xc932, 0x0c66, 0xd746, 0xf2bf, 0x2607, }; int main(void) { int i, j; int fail = 0, pass = 0; for (i = 0; i < COUNTOF(test_crc32); i++) { unsigned long crc = crc32_update(0, test_input, i); if (crc != test_crc32[i]) { fail++; printf("FAIL: crc32%3d, want %08lx, got %08lx\n", i, test_crc32[i], crc); } else { pass++; } crc = 0; for (j = 0; j < i; j++) { crc = crc32_update(crc, test_input + j, 1); } if (crc != test_crc32[i]) { fail++; printf("FAIL: crc32%3d (incremental), want %08lx, got %08lx\n", i, test_crc32[i], crc); } else { pass++; } } for (i = 0; i < COUNTOF(test_crc32); i++) { unsigned long crc = crc32c_update(0, test_input, i); if (crc != test_crc32c[i]) { fail++; printf("FAIL: crc32c%3d, want %08lx, got %08lx\n", i, test_crc32c[i], crc); } else { pass++; } crc = 0; for (j = 0; j < i; j++) { crc = crc32c_update(crc, test_input + j, 1); } if (crc != test_crc32c[i]) { fail++; printf("FAIL: crc32c%3d (incremental), want %08lx, got %08lx\n", i, test_crc32c[i], crc); } else { pass++; } } for (i = 0; i < COUNTOF(test_adler32); i++) { unsigned long pre, suf; unsigned long r = adler32_update(1, test_input, i); if (r != test_adler32[i]) { fail++; printf("FAIL: adler32%3d, want %08lx, got %08lx\n", i, test_adler32[i], r); } else { pass++; } r = 1; for (j = 0; j < i; j++) { r = adler32_update(r, test_input + j, 1); } if (r != test_adler32[i]) { fail++; printf("FAIL: adler32%3d (incremental), want %08lx, got %08lx\n", i, test_adler32[i], r); } else { pass++; } pre = adler32_update(1, test_input, (i+1)/2); suf = adler32_update(1, test_input + (i+1)/2, i/2); r = adler32_combine(pre, suf, i/2); if (r != test_adler32[i]) { fail++; printf("FAIL: adler32%3d (combine), want %08lx, got %08lx\n", i, test_adler32[i], r); } else { pass++; } } for (i = 0; i < COUNTOF(test_crc16x25); i++) { unsigned crc = crc16x25_update(0, test_input, i); if (crc != test_crc16x25[i]) { fail++; printf("FAIL: crc16x25%3d, want %04x, got %04x\n", i, test_crc16x25[i], crc); } else { pass++; } crc = 0; for (j = 0; j < i; j++) { crc = crc16x25_update(crc, test_input + j, 1); } if (crc != test_crc16x25[i]) { fail++; printf("FAIL: crc16x25%3d (incremental), want %04x, got %04x\n", i, test_crc16x25[i], crc); } else { pass++; } } if (fail) { printf("%d tests failed\n", fail); return 1; } printf("All %d tests passed\n", pass); return 0; }
C
#include<stdio.h> int main() { float cel,fr; printf("enter the temprature in fr"); scanf("%f",&fr); cel=5.0/9.0*(fr-32); printf("temprature in cel=%f",cel); return 0; }
C
/*GPIO_InitTypeDef has 5 options: GPIO_Pin: Choose pins you will use for set settings GPIO_Mode: Choose mode of operation. Look down for options GPIO_OType: Choose output type GPIO_PuPd: Choose pull resistor GPIO_Speed: Choose pin speed */ #include "stm32f4xx.h" #include "stm32f4xx_rcc.h" #include "stm32f4xx_gpio.h" void Delay(__IO uint32_t nCount) { while (nCount--); } int main(void) { //RCC(reset and clock control) ile AHB1 bus'indaki(butun GPIO'lar bu bus a bagli) A ve D portlarinda clock enable edilir RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE); //button pin_A0 da ////kart uzerindaki internal ledler D portunda 12-13-14 uncu pinlerde GPIO_InitTypeDef GPIO_InitDef; GPIO_InitDef.GPIO_Pin = GPIO_Pin_13; GPIO_InitDef.GPIO_Mode = GPIO_Mode_OUT; GPIO_InitDef.GPIO_OType = GPIO_OType_PP; GPIO_InitDef.GPIO_PuPd = GPIO_PuPd_NOPULL;//pin output oldugu icin gerek yok GPIO_InitDef.GPIO_Speed = GPIO_Speed_2MHz; GPIO_Init(GPIOD, &GPIO_InitDef); /////////////button///////////////// GPIO_InitDef.GPIO_Pin = GPIO_Pin_0; GPIO_InitDef.GPIO_Mode = GPIO_Mode_IN; GPIO_InitDef.GPIO_OType = GPIO_OType_PP;//Output type push-pull GPIO_InitDef.GPIO_PuPd = GPIO_PuPd_DOWN;//With pull down resistor yani buttona bastigimizda 1 olacak basili degilken 0 GPIO_InitDef.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOA, &GPIO_InitDef); while(1){ if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0)==1) { Delay(8000000);//1 sn bekletiyorum yoksa elimi butondan cekene kadar tekrar toggle oluyor GPIO_ToggleBits(GPIOD, GPIO_Pin_13); } } }
C
//common anode display in reverse #include<pic.h> //header files /*PRIVATE FUNCTION DECLARATION*/ void delay(unsigned int); //function to generate delay //gfedcba void main() { //1 will be off 0 will be ON int n[10] = {0b1000000,0b1111001,0b0100100,0b0110000,0b0011001,0b0010010,0b0000010,0b1111000,0b0000000,0b0011000}; //Codes for numbers TRISC=0x00; //Set PORTC pins as output int i; //Number variable for(i=0;i<10;i++) //Loop will run 10 times { PORTC=n[9-i]; //display no in reverse delay(20000); //delay function call } } /*PRIVATE FUNCTION DEFINITION*/ void delay(unsigned int x) //function to generate delay { while(x>0) //loop runs x times x--; //Decrement x }
C
#include<stdio.h> #include<math.h> int main() { int arr[10],n,i,count; printf("Enter how many distance"); scanf("%d",&n); printf("Enter the distance to be reached"); for(i=0;i<n;i++) { scanf("%d",&arr[i]); } for(i=0;i<n;i++) { if(arr[i]<0) { printf("The distance can't be reached"); } count=0; j=0; while(j<10) { if((2^j)==arr[i]) { printf("True"); count=1; } } if(count==0) { printf("False"); } } return 0; }
C
#include "arvoreRN.h" #include <stdlib.h> #include <stdio.h> #include <unistd.h> /*int main() { arvore *inicio = (arvore*)malloc(sizeof(arvore)); inicio->raiz = NULL; // Atribuição de valores int valor1 = 12, valor2 = 2, valor3 = 13, valor4 = 32, valor5 = 1, valor6 = 10, valor7 = 4, valor8 = 0; // Inserir valores Inserir(inicio, Alocar(valor1)); Inserir(inicio, Alocar(valor2)); Inserir(inicio, Alocar(valor3)); Inserir(inicio, Alocar(valor4)); Inserir(inicio, Alocar(valor5)); Inserir(inicio, Alocar(valor6)); Inserir(inicio, Alocar(valor7)); Inserir(inicio, Alocar(valor8)); // Exibindo printf("\nEM ORDEM: \n"); PercurssoEmOrdem(inicio->raiz); printf("\nPRE ORDEM: \n"); PercurssoPreOrdem(inicio->raiz); printf("\nPOS ORDEM: \n"); PercurssoPosOrdem(inicio->raiz); printf("\n"); int alt = AlturaPreta(inicio->raiz); printf("Altura da Arvore Preta: %d\n", alt); }*/ int main(int argc, char **argv) { arvore *inicio = (arvore*)malloc(sizeof(arvore)); FILE* Salvar; char op; if(argc > 5) { exit(-1); } while((op = getopt(argc, argv, "o:f:")) > 0 ) { switch(op){ case 'f': Salvar = fopen(optarg, "rb"); int receber; while(fscanf(Salvar, "%d", &receber)!=EOF) { //printf("AQUIII\n"); Inserir(inicio, Alocar(receber)); //PercurssoPreOrdem(inicio->raiz); } printf("\nPRE ORDEM: \n"); PercurssoPreOrdem(inicio->raiz); printf("\n"); fclose(Salvar); case 'o': Salvar = fopen(optarg, "wb+"); int gravar; } } }
C
#include<stdio.h> int main() { int a,b,c,i,j,s=0,cnt=0,k=0; scanf("%d %d %d",&a,&b,&c); for(i=1;i<=a*c;i++) { if(i*b+b>=a) { s=i*b+b; for(j=2;j<=c;j++) { if(s+b>=a*j) { cnt++; s+=b; } else { s=0; cnt=0; break; } } if(cnt==c-1) { k++; printf("%d",i); break; } } if(k==1) break; } return(0); }
C
#include <stdio.h> #define SOLVE_MODE 1 /********************************************** Function Name : vSolveTraingle Developer : Jack Kilby First Breed : 2018-06-08 Update : 2018-06-08 Description : Solve Traingle by some known conditions SOLVE_MODE == 1, means solve the traingle with 3 known sides. Return : void Parametric : none **********************************************/ void vSolveTraingle() { #if SOLVE_MODE == 1 float a,b,c; printf("Tell me the 3 sides of your traingle <a,b,c>:"); scanf("%f,%f,%f",&a,&b,&c); //First Step, Make sure the 3 sides can construct a traingle. if ((a + b <= c) || (a + c <= b) || (b + c <= a)) { printf("Sorry, your 3 sides can not construct a traingle"); return; } //Second tep, Get the sides order by length order a < b < c with Bubbling Method. float temp; if(a > b) { temp = a; a = b; b = temp; } else { if(b > c) { temp = b; b = c; c = temp; } } //Third Step, Make sure what kind of traingle this is. if( a*a + b*b == c*c) { if(a == b) { printf("This is a ֱ."); } else { printf("This is a ֱ."); } } else { if(a == b) { if (a == c) { printf("This is a ȱ."); } else { printf("This is a ."); } } else { printf("This is a /۽ "); } } #endif } int main() { vSolveTraingle(); return 0; }
C
// program C, care primeste ca si argumente nume de fisiere, pt fiecare argument se lanseaza cate un thread care // a) determinam numarul de cuvinte din fisier si calculez media numarului de cuvinte. #include<stdio.h> #include<stdlib.h> #include<pthread.h> #include<string.h> pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; #define N 100 int medie; void* func(void* ar){ FILE* pt; char cmd[N], result[N]; strcpy(cmd, "cat "); strcat(cmd, ar); strcat(cmd, "| wc -w"); pt = popen(cmd, "r"); fgets(result, 20, pt); pclose(pt); puts(ar); printf(" numar cuvinte: %s \n", result); int j; j = atoi(result); pthread_mutex_lock(&m); medie = medie + j; pthread_mutex_unlock(&m); return NULL; } int main(int argc, char* argv[]){ pthread_t t[20]; int i; for( i=1; i<argc; i++){ pthread_create( &t[i], NULL, func, argv[i]); pthread_join( t[i], NULL); } medie = medie / (argc-1); printf("Medie= %d\n", medie); return 0; }
C
#include <sys/mman.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include "mem.h" int m_error; struct Node { int size; struct Node *next; }; struct Node *headFree = NULL; struct Node *listPrev = NULL; int init = 1; int Mem_Init(int sizeOfRegion,int debug) { if (sizeOfRegion <= 0 || init == 0) { m_error = E_BAD_ARGS; return -1; } if (sizeOfRegion % getpagesize() != 0) sizeOfRegion += sizeOfRegion - (sizeOfRegion % getpagesize()); struct Node *freeNode; int fd = open("/dev/zero/", O_RDWR); void *ptr = mmap(NULL, sizeOfRegion, PROT_READ | PROT_WRITE, MAP_ANON|MAP_PRIVATE, fd, 0); if (ptr == MAP_FAILED) { perror("mmap"); exit(1); } freeNode = (struct Node *)ptr; freeNode->size = sizeOfRegion; freeNode->next = NULL; headFree = freeNode; close(fd); init = 0; return 0; } struct Node *addSizeToNode(struct Node *node, int val) { void *ptr =(void *) node; ptr += val; return (struct Node *) ptr; } void *chunkNode(struct Node *node, int size) { struct Node *newNode; newNode = node; if (size % 8 == 0) size += sizeof(struct Node); else{ int i = size/8; size = (i+1)*8 + sizeof(struct Node); } int sizeOfRegion = node->size; struct Node *next = node->next; node = addSizeToNode(node, size); node->size = sizeOfRegion - size; if (node->size == 0 && listPrev != NULL) { listPrev->next = next; } else if (node->size == 0 && listPrev == NULL) { headFree = NULL; } else { if(listPrev != NULL)listPrev->next = node; node->next = next; } if (headFree == newNode) headFree = node; newNode->size = size; newNode->next = NULL; return (void *) newNode + sizeof(struct Node); } void *getWorstFit(int size) { struct Node *worst = NULL; struct Node *node = headFree; struct Node *prev = NULL; while (node != NULL) { // printf("infinite while"); if (worst == NULL || node->size > worst->size) { worst = node; listPrev = prev; } prev = node; node = node->next; } return (worst->size >= size + sizeof(struct Node)) ? worst : NULL; } void *Mem_Alloc(int size) { struct Node *worstFit = getWorstFit(size); if (worstFit == NULL) { m_error = E_NO_SPACE; return NULL; } return chunkNode(worstFit,size); } void *findNeighborNode(struct Node *node) { struct Node *curr = headFree; struct Node *prev = NULL; int coalesced = 0; while (curr != NULL) { //node at end of free list element if (node == addSizeToNode(curr, curr->size)) { curr->size += node->size; //take out of free list and add to head if (!coalesced) { if (curr != headFree) { prev->next = curr->next; curr->next = headFree; headFree = curr; node = curr; curr = prev; } else { node = curr; } coalesced = 1; } else { prev->next = curr->next; curr->next = node->next; headFree = curr; return curr; } } //node at beginning of free list element else if (curr == addSizeToNode(node, node->size)) { //add free list element to node node->size += curr->size; //take free list element out of list and add new element at head if (!coalesced) { if (curr != headFree) { prev->next = curr->next; node->next = headFree; curr = prev; headFree = node; } else { node->next = curr->next; curr = node; headFree = node; } coalesced = 1; } else { prev->next = curr->next; return node; } } prev = curr; curr = curr->next; } //if not coalesced with any elements, add to head of list if(!coalesced){ node->next = headFree; headFree = node; } return node; } int Mem_Free(void *ptr) { if (ptr == NULL) return 0; ptr -= sizeof(struct Node); struct Node *node = (struct Node *) ptr; node = findNeighborNode(node); return 0; } void Mem_Dump() { } void printList() { int i = 0; struct Node * curr = headFree; while(curr != NULL) { printf("list member:%p\nlist index:%d\nlist size:%d\n", (void *) curr, i, curr->size); curr=curr->next; i++; } }
C
#ifndef SYM_VEC_H_ #define SYM_VEC_H_ #include <string.h> #include <limits.h> #include <ctype.h> #define EPSILON 0 #define INT_IN_BITS ((signed)(8*sizeof(long))) #define RE_SYM_VEC_LEN ((signed)((CHAR_MAX+1)/INT_IN_BITS)) typedef long SymbolVector[RE_SYM_VEC_LEN]; inline int legalChar(char c) { return isspace(c) || isgraph(c); } int isCharClass(char c) { c = tolower(c); return c == 'w' || c == 'd'; } int isCharClassMember(char c, char classCode) { int isMember; switch (tolower(classCode)) { case 'w': isMember=isalnum(c) || c == '_'; break; case 'd': isMember=isdigit(c); break; default: return 0; } return islower(classCode) ? isMember : !isMember; } inline SymbolVector *symbolVector() { SymbolVector *symVec=(SymbolVector *)malloc(sizeof(SymbolVector)); memset(symVec, 0, sizeof(SymbolVector)); return symVec; } inline void addSymbol(SymbolVector *symVec, char symbol) { int index, bit; if (!symVec) return; index=symbol/INT_IN_BITS; bit=symbol%INT_IN_BITS; if (index >= RE_SYM_VEC_LEN) return; (*symVec)[index]|= 1 << bit; } inline void removeSymbol(SymbolVector *symVec, char symbol) { int index, bit; if (!symVec) return; index=symbol/INT_IN_BITS; bit=symbol%INT_IN_BITS; if (index >= RE_SYM_VEC_LEN) return; (*symVec)[index]&= ~(1 << bit); } inline int symVecContains(SymbolVector *symVec, char symbol) { int index, bit; if (!symVec) return 0; index=symbol/INT_IN_BITS; bit=symbol%INT_IN_BITS; if (index >= RE_SYM_VEC_LEN) return 0; return (*symVec)[index] & (1 << bit); } inline void symVecCompliment(SymbolVector *sv, SymbolVector *res) { int index; for (index=0; index < RE_SYM_VEC_LEN; ++index) (*res)[index]=~(*sv)[index]; } inline void symVecAnd(SymbolVector *sv1, SymbolVector *sv2, SymbolVector *res) { int index; for (index=0; index < RE_SYM_VEC_LEN; ++index) (*res)[index]=(*sv1)[index] & (*sv2)[index]; } inline void symVecOr(SymbolVector *sv1, SymbolVector *sv2, SymbolVector *res) { int index; for (index=0; index < RE_SYM_VEC_LEN; ++index) (*res)[index]=(*sv1)[index] | (*sv2)[index]; } inline void symVecXor(SymbolVector *sv1, SymbolVector *sv2, SymbolVector *res) { int index; for (index=0; index < RE_SYM_VEC_LEN; ++index) (*res)[index]=(*sv1)[index] ^ (*sv2)[index]; } inline void symVecClear(SymbolVector *symVec) { memset(symVec, 0, sizeof(SymbolVector)); } inline SymbolVector *epsilonVector() { SymbolVector *eps=symbolVector(); addSymbol(eps, EPSILON); return eps; } #endif /* SYM_VEC_H_ */
C
#pragma once //V̂̃f[^̍\ //V̂̎OW typedef struct star_pos { float px; float py; float pz; }; //V̂̎Ox typedef struct star_vel { float vx; float vy; float vz; }; //V̂̎Ox typedef struct star_acc { float ax; float ay; float az; }; //V̂̏ typedef struct star_inf { float m; star_pos st_p; star_vel st_v; star_acc st_a; };
C
/* Программа 2 (06-1b.с) для иллюстрации работы с разделяемой памятью */ /* Мы организуем разделяемую память для массива из трех целых чисел. Первый элемент массива является счетчиком числа запусков программы 1, т. е. данной программы, второй элемент массива – счетчиком числа запусков программы 2, третий элемент массива – счетчиком числа запусков обеих программ */ #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> int main() { int *array; /* Указатель на разделяемую память */ int shmid; /* IPC дескриптор для области разделяемой памяти */ int new = 1; /* Флаг необходимости инициализации элементов массива */ char pathname[] = "06-1a.c"; /* Имя файла, используемое для генерации ключа. Файл с таким именем должен существовать в текущей директории */ key_t key; /* IPC ключ */ /* Генерируем IPC ключ из имени файла 06-1a.c в текущей директории и номера экземпляра области разделяемой памяти 0 */ if((key = ftok(pathname,0)) < 0){ printf("Can\'t generate key\n"); exit(-1); } /* Пытаемся эксклюзивно создать разделяемую память для сгенерированного ключа, т.е. если для этого ключа она уже существует, системный вызов вернет отрицательное значение. Размер памяти определяем как размер массива из трех целых переменных, права доступа 0666 – чтение и запись разрешены для всех */ if((shmid = shmget(key, 3*sizeof(int), 0666|IPC_CREAT|IPC_EXCL)) < 0){ /* В случае возникновения ошибки пытаемся определить: возникла ли она из-за того, что сегмент разделяемой памяти уже существует или по другой причине */ if(errno != EEXIST){ /* Если по другой причине – прекращаем работу */ printf("Can\'t create shared memory\n"); exit(-1); } else { /* Если из-за того, что разделяемая память уже существует, то пытаемся получить ее IPC дескриптор и, в случае удачи, сбрасываем флаг необходимости инициализации элементов массива */ if((shmid = shmget(key, 3*sizeof(int), 0)) < 0) { printf("Can\'t find shared memory\n"); exit(-1); } new = 0; } } /* Пытаемся отобразить разделяемую память в адресное пространство текущего процесса. Обратите внимание на то, что для правильного сравнения мы явно преобразовываем значение -1 к указателю на целое.*/ if((array = (int *)shmat(shmid, NULL, 0)) == (int *)(-1)) { printf("Can't attach shared memory\n"); exit(-1); } /* В зависимости от значения флага new либо инициализируем массив, либо увеличиваем cоответствующие счетчики */ if(new){ array[0] = 0; array[1] = 1; array[2] = 1; } else { array[1] += 1; array[2] += 1; } /* Печатаем новые значения счетчиков, удаляем разделяемую память из адресного пространства текущего процесса и завершаем работу */ printf("Program 1 was spawn %d times, program 2 - %d times, total - %d times\n", array[0], array[1], array[2]); // printf("Program 1 was spawn %d times, program 2 - %d times, " + \ // "total - %d times\n", array[0], array[1], array[2]); if(shmdt(array) < 0){ printf("Can't detach shared memory\n"); exit(-1); } return 0; }
C
#include <stdio.h> #include <errno.h> #include <unistd.h> #include <getopt.h> #include <stdlib.h> #include <pthread.h> #include <time.h> #include <string.h> #include <sched.h> #include <stdint.h> #include "SortedList.h" int thdnum = 1; int itenum = 1; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int spin_lock = 0; char *setting; int opt_yield; SortedList_t *list; SortedListElement_t **element; void element_init(); void* threads_opt(void *id); int main(int argc, char *argv[]) { struct option long_options[] = { {"threads", optional_argument, NULL, 1}, {"iterations", optional_argument, NULL, 2}, {"sync", required_argument, NULL, 3}, {"yield", required_argument, NULL, 4}, {0, 0, 0, 0} }; while(1) { int opt_flag = getopt_long(argc, argv, "", long_options, NULL); if (opt_flag == -1) { break; } switch (opt_flag){ case 1: { thdnum = atoi(optarg); break; } case 2: { itenum = atoi(optarg); break; } case 3: { setting = optarg; if (*setting != 'm' && *setting != 's') { fprintf(stderr, "invalid sync argument\n"); exit(1); } break; } case 4: { int i = 0; while (*(optarg + i) != '\0') { switch(*(optarg + i)) { case 'i': opt_yield |= INSERT_YIELD; break; case 'd': opt_yield |= DELETE_YIELD; break; case 'l': opt_yield |= LOOKUP_YIELD; break; default: fprintf(stderr, "invalid yield argument\n"); exit(1); break; } ++i; } break; } default: { exit(1); } } } list = (SortedListElement_t *) malloc(sizeof(SortedList_t*)); list -> prev = list; list -> next = list; list -> key = NULL; element = (SortedListElement_t **) malloc(itenum * thdnum * sizeof(SortedListElement_t*)); element_init(); struct timespec start_time; if (clock_gettime(CLOCK_MONOTONIC, &start_time)) { int ernum = errno; fprintf(stderr, "ending clock failed with error%s\n", strerror(ernum)); exit(1); } pthread_t threads[thdnum]; for (int i = 0; i < thdnum; ++i) { int id = i; int ret = pthread_create(&threads[i], NULL, threads_opt,(void *) (intptr_t)id); if (ret) { int ernum = errno; fprintf(stderr, "creating threads failed with error%s\n", strerror(ernum)); exit(1); } } for (int j = 0; j < thdnum; ++j) { int ret = pthread_join(threads[j], NULL); if (ret) { int ernum = errno; fprintf(stderr, "joining threads failed with error%s\n", strerror(ernum)); exit(1); } } struct timespec end_time; if (clock_gettime(CLOCK_MONOTONIC, &end_time)) { int ernum = errno; fprintf(stderr, "ending clock failed with error%s\n", strerror(ernum)); exit(1); } if (SortedList_length(list) != 0) { fprintf(stderr, "list not empty after operation\n"); exit(2); } printf("list-"); if (opt_yield & INSERT_YIELD) { printf("i"); } if (opt_yield & DELETE_YIELD) { printf("d"); } if (opt_yield & LOOKUP_YIELD) { printf("l"); } if (opt_yield == 0) { printf("none"); } printf("-"); if (setting == NULL) { printf("none"); }else { printf("%s", setting); } long long total_time = (end_time.tv_sec - start_time.tv_sec) * 1000000000; long long optnum = thdnum * itenum * 3; total_time += end_time.tv_nsec; total_time -= start_time.tv_nsec; long long ave_time = total_time / optnum; printf(",%d,%d,1,%lld,%lld,%lld\n", thdnum, itenum, optnum, total_time, ave_time); return 0; } void* threads_opt(void *id) { int t_id = (intptr_t)id; if (setting != NULL && *setting == 'm') { if(pthread_mutex_lock(&mutex)) { int ernum = errno; fprintf(stderr, "failed grabbing the lock, with error%s\n", strerror(ernum)); exit(1); } } if (setting != NULL && *setting == 's') { while(__sync_lock_test_and_set(&spin_lock, 1)); } for (int i = t_id; i < itenum * thdnum; i += thdnum) { SortedList_insert(list, element[i]); } int list_length = SortedList_length(list); if (list_length == -1) { fprintf(stderr, "corrtuped list\n"); exit(2); } for (int j = t_id; j < itenum * thdnum; j += thdnum) { SortedListElement_t *curr; curr = SortedList_lookup(list, element[j] -> key); if (curr == NULL) { continue; } if(SortedList_delete(curr) == 1) { fprintf(stderr, "corrtuped prev/next pointers\n"); exit(2); } } if (setting != NULL && *setting == 'm') { if(pthread_mutex_unlock(&mutex)) { int ernum = errno; fprintf(stderr, "failed grabbing the lock, with error%s\n", strerror(ernum)); exit(1); } } if (setting != NULL && *setting == 's') { __sync_lock_release(&spin_lock, 1); } pthread_exit(NULL); } void element_init() { char pool[63] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; for (int i = 0; i < itenum * thdnum; i++) { char key[11] = ""; for (int j = 0; j < 10; j++) { key[j] = pool[rand() % 62]; } element[i] = (SortedList_t*)malloc(sizeof(SortedList_t*)); element[i] -> prev = NULL; element[i] -> next = NULL; element[i] -> key = (const char *)&key; } }
C
#include <stdio.h> #include <omp.h> #include <time.h> #define INT_MAX 2147483647 double monte_carlo_pi() { const size_t N = 100000; double step; double x, pi, sum = 0.; step = 1. / (double)N; double start, end; int circle_darts = 0; omp_set_num_threads(2); start = omp_get_wtime(); #pragma omp parallel shared(circle_darts) { int thread_id = omp_get_thread_num(); unsigned int seed_x = 123 * (thread_id + 1); unsigned int seed_y = 124 * (thread_id + 1); double x, y; #pragma omp for schedule(dynamic, N / 2) \ reduction(+: circle_darts) \ private(x, y) for (int i = 0; i < N; ++i) { x = ((double) rand_r(&seed_x)) / (double) INT_MAX; y = ((double) rand_r(&seed_y)) / (double) INT_MAX; x = (i + 0.5) * step; sum += 4.0 / (1. + x * x); } } pi = step * sum; end = omp_get_wtime(); printf("parallel monte-carlo pi = %.16f, time = %f\n", pi, (double)(end - start)); return pi; } int main() { const size_t N = 100000; double step; double x, pi, sum = 0.; step = 1. / (double)N; for (int i = 0; i < N; ++i) { x = (i + 0.5) * step; sum += 4.0 / (1. + x * x); } pi = step * sum; printf("pi = %.16f\n", pi); monte_carlo_pi(); return 0; }
C
#include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #include <pthread.h> #include <signal.h> #include <semaphore.h> #include <errno.h> #include "helpers.h" #define SA struct sockaddr pthread_t* send_threads; pthread_t* recv_threads; /* Semaphore used to synchronize send/recv msg threads. The 'send_msg' thread can not send messages until it receives the ip from server */ sem_t sem_IP; /* Current client IP and listening port for peer to peer transmision */ cli_info_t cli_info; /* Flag to mark that a set of files are currently trensfering */ int file_is_sending = 0; void* send_file(void* param_send); void* recv_file(void* thread_nb); void* send_msg(void* fd); void* receive_msg(void* fd); /* Reads a message from keyboard into the buffer and sends to the channel defined by sockfd. When 'file' is typed, the content of the send directory is listed and the user has to introduce the number of files he wants to send, then the name of each file. */ void *send_msg(void* fd) { int *fd_server = (int *)fd; int return_val, i; char buffer[MAX]; char buff_ser[MAX]; int sockfd; param_send_t* files_details; struct sockaddr_in serv_addr; while (1) { fgets(buffer, MAX, stdin); printf("\n"); /* Check if the user wants to send some files */ if (strncmp(buffer, "file", 4) == 0 && strlen(buffer) == 5) { /* If there is not already a transfer in progress, go further. A transfer is also when more files are currently sending*/ if (!file_is_sending) { list_dir(); int files_nb = choose_files_nb(); if (files_nb < 1) { continue; } /* Introduce the file names and check if files exist */ files_details = (param_send_t *)calloc(files_nb, sizeof(param_send_t)); CHECK(files_details == NULL, "Fail to alloc memory"); return_val = choose_files(files_nb, files_details); if (return_val == 0) { continue; } /* Send the 'file' message to the other client to be prepared for receiving */ sprintf(buffer, "%d-file\n", CTRL_FILE); send_chunk(buffer, *fd_server); file_is_sending = 1; sem_wait(&sem_IP); /* Open the server's socket on which it accepts connections from clients */ sockfd = socket(AF_INET, SOCK_STREAM, 0); CHECK(sockfd < 0, "Fail to create sockfd"); /* Set server's details: IPV4, address, port */ serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(PORT_FILE); bzero(&(serv_addr.sin_zero),8); /* Associate a port to the server's socket. If the port is already assigned, choose another one, by incrementing the current port */ int port = PORT_FILE; do { return_val = bind(sockfd, (struct sockaddr*)&serv_addr, sizeof(struct sockaddr)); CHECK(return_val < 0 && errno != EADDRINUSE, "Failed to bind"); if (return_val == -1) { port += 2; serv_addr.sin_port = htons(port); } } while(return_val == -1); return_val = listen(sockfd, 5); CHECK(return_val != 0, "Listen fails"); cli_info.port = ntohs(serv_addr.sin_port); /* Send the IP & port to the server->other client for peer-to-peer connection */ sprintf(buffer, "%d-%s-%d", CTRL_P_IP, cli_info.IP, cli_info.port); send_chunk(buffer, *fd_server); /* Send the number of files to be waited by the other client */ sprintf(buffer, "%d-%d", CTRL_FILE, files_nb); send_chunk(buffer, *fd_server); /* Allocate space for another files_nb + 1 threads - files_nb threads, 1 thread for one file to transfer - 1 thread to send messages(because the current one is blocked by the sys-call join_thread) */ send_threads = (pthread_t *)realloc(send_threads, (files_nb + 3) * sizeof(pthread_t)); return_val = pthread_create(&send_threads[2], 0, send_msg, (void *)fd_server); for (i = 0; i < files_nb; ++i) { files_details[i].fd = sockfd; files_details[i].thread_nb = i; return_val = pthread_create(&send_threads[i + 3], 0, send_file, (void *)(files_details) + i * sizeof(param_send_t)); CHECK(return_val != 0, "Failed to create thread"); printf("_____Created SEND thread nb=%d from %d_____\n", i+1, files_nb); } for (i = files_nb + 2; i > 1; --i) { return_val = pthread_join(send_threads[i], 0); CHECK(return_val != 0, "Failed to join thread"); } free(files_details); return_val = close(sockfd); CHECK(return_val < 0, "Error closing socket"); send_threads = (pthread_t *)realloc(send_threads, 2 * sizeof(pthread_t)); file_is_sending = 0; } else { printf("Another file is sending now. Please wait\n"); } continue; } serial_msg(buffer, buff_ser, TXT_MSG); return_val = send(*fd_server, buff_ser, MAX, 0); CHECK(return_val < 0, "Client fails sending message to server"); if (is_fin_msg(buff_ser)) { pthread_cancel(send_threads[1]); return 0; } } return 0; } /* Function which receives a message from server and print it */ void *receive_msg(void* fd) { int *fd_server = (int *)fd; int return_val, i; char buffer[MAX]; int files_nb = 0; int *thread_nb; while (1) { recv_chunk(buffer, *fd_server); if (is_fin_msg(buffer)) { printf("fin\n"); pthread_cancel(send_threads[0]); break; } if (is_file_msg(buffer)) { recv_chunk(buffer, *fd_server); parse_ip_port(buffer, &cli_info); printf("_____Client connects to the other client: IP=%s, PORT=%d_____\n", cli_info.IP, cli_info.port); /* Receive the number of files */ recv_chunk(buffer, *fd_server); files_nb = get_files_nb(buffer); recv_threads = (pthread_t *)realloc(recv_threads, (files_nb + 1) * sizeof(pthread_t)); return_val = pthread_create(&recv_threads[0], 0, receive_msg, fd); CHECK(return_val != 0, "Failed to create thread"); thread_nb = (int*)calloc(files_nb, sizeof(int)); for (i = 0; i < files_nb; ++i) { thread_nb[i] = i; return_val = pthread_create(&recv_threads[i + 1], 0, recv_file, (void*)(thread_nb) + i * sizeof(int)); CHECK(return_val != 0, "Failed to create thread"); printf("_____Created RECV thread %d from %d_____\n", i + 1, files_nb); } for (i = files_nb; i >= 0; --i) { return_val = pthread_join(recv_threads[i], 0); CHECK(return_val != 0, "Failed to join thread"); } continue; } else if (is_ctrl(buffer, CTRL_IP)) { sem_post(&sem_IP); strcpy(cli_info.IP, buffer); continue; } /* Display the message received from the server */ get_content(buffer, buffer); printf("Server: "); puts(buffer); } return 0; } void *send_file(void* param_send) { param_send_t p_send = *(param_send_t*)param_send; FILE* fp = (FILE*)p_send.other; int f_size; char buffer[MAX]; char buff_ser[MAX]; int fd, return_val; struct sockaddr_in cli; socklen_t len_cli; fd = accept(p_send.fd, (struct sockaddr*)&cli, &len_cli); CHECK(fd < 0, "Fail accepting client"); f_size = fsize(fp); /* Send the filename to the server */ serial_msg(p_send.file_name, buffer, CTRL_FILE); send_chunk(buffer, fd); /* Send the number of chunks of the file to the server */ sprintf(buffer, "%d", f_size); serial_msg(buffer, buff_ser, CTRL_FILE); send_chunk(buff_ser, fd); while (fgets(buffer, MAX, fp) != NULL) { /* Send each chunk of the file to the server */ serial_msg(buffer, buff_ser, CTRL_FILE); sleep(NB_WAIT_SEC); send_chunk(buff_ser, fd); } printf("_____File successfully sent_____\n\n"); return_val = fclose(fp); CHECK(return_val != 0, "Fail to close file stream"); return_val = close(fd); CHECK(return_val < 0, "Error closing socket"); if (p_send.thread_nb == 0) { pthread_cancel(send_threads[2]); } return NULL; } void* recv_file(void* thread_nb) { FILE* fp = NULL; int thread_id = *(int*)thread_nb; int f_size, return_val; int sockfd; char *file_name; char buffer[MAX]; struct sockaddr_in servaddr; sockfd = socket(AF_INET, SOCK_STREAM, 0); CHECK(sockfd <= 0,"Fail creating client socket\n"); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = inet_addr(cli_info.IP); servaddr.sin_port = htons(cli_info.port); return_val = connect(sockfd, (SA*)&servaddr, sizeof(servaddr)); CHECK(return_val != 0, "Cannot connect to the server\n"); /* Receive the file name */ recv_chunk(buffer, sockfd); get_content(buffer, buffer); /* Create the full path to recv directory */ file_name = (char *)malloc(sizeof(RCV_DIR) + strlen(buffer)); sprintf(file_name, "%s%s", RCV_DIR, buffer); /* Open destination file */ fp = fopen(file_name, "w"); CHECK(fp == NULL, "Failed to open destination file"); /* Receive the file dimension */ recv_chunk(buffer, sockfd); get_content(buffer, buffer); f_size = atoi(buffer); /* Receive the content while the size already received is > 0, and decrement the number of bytes at each step */ while (f_size > 0) { int nb_B_recv = recv_chunk(buffer, sockfd); get_content(buffer, buffer); sleep(NB_WAIT_SEC); f_size -= nb_B_recv; fputs(buffer, fp); } printf("_____File successfully received_____\n"); return_val = fclose(fp); CHECK(return_val != 0, "Fail to close file stream"); return_val = close(sockfd); CHECK(return_val < 0, "Error closing socket"); if (thread_id == 0) { pthread_cancel(recv_threads[0]); CHECK(return_val != 0, "Fail to cancel thread"); } return 0; } int main(int argc, char* argv[]) { char buff_recv[MAX]; int sockfd; int return_val; struct sockaddr_in servaddr; send_threads = (pthread_t *)calloc(2, sizeof(pthread_t)); if (argc < 3) { printf("Args: parameter for server's ip&port is missing\n"); exit(0); } sem_init(&sem_IP, 0, 0); sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd != -1) { printf("Success creating client socket\n"); } else { printf("Failed creating client socket\n"); } bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; // argv[1] is the server's ip servaddr.sin_addr.s_addr = inet_addr(argv[1]); // argv[2] is the server's port on which it is listening servaddr.sin_port = htons(atoi(argv[2])); return_val = connect(sockfd, (SA*)&servaddr, sizeof(servaddr)); CHECK(return_val != 0, "Cannot connect to the server\n"); // Client is waiting for hello message from server bzero(buff_recv, MAX); recv_chunk(buff_recv, sockfd); printf("Server: %s\n", buff_recv); /* Create 2 threads: - one to receive messages - one to send messages */ // create_main_threads(&sockfd); return_val = pthread_create(&send_threads[0], 0, send_msg, (void *)&sockfd); CHECK(return_val != 0, "Failed to create thread"); return_val = pthread_create(&send_threads[1], 0, receive_msg, (void *)&sockfd); CHECK(return_val != 0, "Failed to create thread"); for (int i = 0; i < 2; ++i) { int return_val = pthread_join(send_threads[i], 0); CHECK(return_val != 0, "Failed to join thread"); } sem_destroy(&sem_IP); return_val = close(sockfd); CHECK(return_val != 0, "Fail closing socket"); free(send_threads); }
C
#include "test_helper.h" #include "rngs.h" #include <math.h> #include "dominion.h" #include <stdio.h> void printHand(struct gameState *game){ int currentPlayer = whoseTurn(game); for (int i = 0; i < game->handCount[currentPlayer]; i++) printf("Hand[%d]: %d\n", i, game->hand[currentPlayer][i]); return; } void printDeck(struct gameState *game){ int currentPlayer = whoseTurn(game); for (int i = 0; i < game->deckCount[currentPlayer]; i++) printf("Deck[%d]: %d\n", i, game->deck[currentPlayer][i]); return; } int flagCheck(int testState, int validFlag) { if (testState == -1 && validFlag == 1) return -1; else if (testState == 1 && validFlag == 1) return 1; else if (testState == -1 && validFlag == -1) return 1; else if (testState == 1 && validFlag == -1) return -1; return 0; } void resetGameState(struct gameState *Game) { int i, j; Game->numPlayers = 0; for (i = 0; i < treasure_map+1; i++){ Game->supplyCount[i] = 0; Game->embargoTokens[i] = 0; } Game->outpostPlayed = 0; Game->outpostTurn = 0; Game->whoseTurn = 0; Game->phase = 0; Game->numActions = 0; Game->coins = 0; Game->numBuys = 0; for (i = 0; i < MAX_PLAYERS; i++){ for (j = 0; j < MAX_HAND; j++) Game->hand[i][j] = 0; Game->handCount[i] = 0; for (j = 0; j < MAX_DECK; j++){ Game->deck[i][j] = 0; Game->discard[i][j] = 0; } Game->deckCount[i] = 0; Game->discardCount[i] = 0; } for (i = 0; i < MAX_DECK; i++) Game->playedCards[i] = 0; Game->playedCardCount = 0; return; } void randomizeKingdomCards(int k[10]) { int i, j, temp; for (i = 0; i < 10; i++) { k[i] = -1; while(k[i] == -1) { temp =(int) ((Random() * (27 - 8) + 8)); for (j = 0; j < i; j++){ if (k[j] == temp){ temp = 0; break; } } if (temp != 0) k[i] = temp; } } return; } void printGame(struct gameState control) { int i, j; printf("numPlayers:\t%d\n", control.numPlayers); printf("supplyCount:\n"); for (i = 0; i <= treasure_map; i++){ printf("\t\t%d", control.supplyCount[i]); ((i%4) == 0) ? printf("\n") : printf(" "); } printf("\n"); printf("embargoTokens:\n"); for (i = 0; i <= treasure_map; i++){ printf("\t\t%d", control.embargoTokens[i]); ((i%4) == 0) ? printf("\n") : printf(" "); } printf("\n"); printf("outpostPlayed:\t%d\n", control.outpostPlayed); printf("Whose Turn:\t%d\n", control.whoseTurn); printf("Phase: \t\t%d\n", control.phase); printf("numActions: \t%d\n", control.numActions); printf("coins:\t\t%d\n", control.coins); printf("numBuys:\t%d\n", control.numBuys); printf("hand:\t\t\n"); for (i = 0; i < control.numPlayers; i++){ for (j = 0; j < control.handCount[i]; j++){ printf("\t\t%d", control.hand[i][j]); ((j % 4)== 0) ? printf("\n") : printf(" "); } printf("\n--------------------------------\n"); } printf("\n"); printf("handCount: \t\n"); for (i = 0; i < control.numPlayers; i++){ printf("\t\t%d", control.handCount[i]); ((i % 4) == 0) ? printf("\n") : printf(" "); } printf("\n"); printf("deck:\t\t\n"); for (i = 0; i < control.numPlayers; i++){ for (j = 0; j < control.deckCount[i]; j++){ printf("\t\t%d", control.deck[i][j]); ((j%4) == 0) ? printf("\n") : printf(" "); } printf("\n----------------------------------\n"); } printf("deckCount:\t\n"); for (i = 0; i < control.numPlayers; i++){ printf("\t\t%d", control.deckCount[i]); ((i % 4) == 0) ? printf("\n") : printf(" "); } printf("\n"); printf("discard:\t\n"); for (i = 0; i < control.numPlayers; i++){ for(j = 0; j < control.discardCount[i]; j++){ printf("\t\t%d", control.discard[i][j]); ((j % 4) == 0) ? printf("\n") : printf(" "); } printf("\n-----------------------------------\n"); } printf("\n"); printf("discardCount:\t\n"); for (i = 0; i < control.numPlayers; i++){ printf("\t\t%d", control.discardCount[i]); ((i % 4) == 0) ? printf("\n") : printf(" "); } printf("\n"); printf("playedCards:\t\n"); for (i = 0; i < control.playedCardCount; i++){ printf("\t\t%d", control.playedCards[i]); ((i % 4) == 0)? printf("\n") : printf(" "); } printf("playedCardCount:%d\t\n", control.playedCardCount); return; }
C
// #pragma once // #include <SFML/System/Vector2.hpp> // // namespace Engine // { // class Vector2f : public sf::Vector2f // { // public: // Vector2f() // : Vector2f(0, 0) // { // } // // virtual ~Vector2f() = default; // // Vector2f(float X, float Y) // : Vector2<float>(X, Y) // { // } // // // Copy Assign/Constructor should make a valid copy of the current object // // e.g. Copy the data from one into the other // // Copy Constructor // Vector2f(const Vector2f& other) // : sf::Vector2f(other) // { // } // // // Copy Assignment // Vector2f& operator=(const Vector2f& other) // { // x = other.x; // y = other.y; // // return *this; // } // // // // Move // Vector2f(Vector2f&& other) noexcept = default; // // // Move // Vector2f& operator=(Vector2f&& other) noexcept = default; // // // friend bool operator==(const Vector2f& lhs, const Vector2f& rhs) // { // return (lhs.x == rhs.x && lhs.y == rhs.y); // } // // friend bool operator!=(const Vector2f& lhs, const Vector2f& rhs) // { // return !(lhs == rhs); // } // // /// Is this vector of length 1? // bool isNormalized() const; // // /// Normalize this vector to a length of 1 // void normalize(); // // /// What is the length of this vector // float length() const; // }; // }
C
/* Interesting! I am currently in the state where new shells seem * to be ignoring SIGPIPE. The symptom is that when I start a new * shell and run 'yes | head', it hangs. I suspect yes is inheriting * the disposition and ignoring SIGPIPE. This probably has to do with * the version of tmux I'm running. So this is a simple wrapper * to reset the disposition and run a command. */ #include <signal.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> void set_default(struct sigaction *act, int s) { if(sigaction(s, act, NULL)) { perror("sigaction"); exit(EXIT_FAILURE); } } int main(int argc, char **argv) { struct sigaction act = {{0}}; sigset_t new; sigemptyset(&new); if(sigprocmask(SIG_SETMASK, &new, NULL)) { perror("sigprocmask"); return EXIT_FAILURE; } act.sa_handler = SIG_DFL; set_default(&act, SIGPIPE); set_default(&act, SIGINT); set_default(&act, SIGTERM); execvp(argv[1], argv+1); perror("execlp"); return EXIT_FAILURE; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define HASH_SIZE 10000 struct hashnode { struct hashnode *next; int key; int cnt; }; struct hash_head { struct hashnode *head; }; struct hash_head *init() { struct hash_head *db; db = (struct hash_head*)malloc(sizeof(struct hash_head) * HASH_SIZE); int i; for (i = 0; i < HASH_SIZE; i ++) { db[i].head = NULL; } return db; } struct hashnode* new_node(int key) { struct hashnode *node; node = (struct hashnode*)malloc(sizeof(struct hashnode)); if (node == NULL) { return NULL; } node->cnt = 1; node->next = NULL; node->key = key; return node; } int get_index(int key) { int real_key = key; while (real_key < 0) { real_key += HASH_SIZE; } return real_key % HASH_SIZE; } int hash_search_rec(struct hash_head *db, int key) { struct hashnode *p; int index = get_index(key); p = db[index].head; if (p == NULL) { return -1; } while(p != NULL) { if (p->key == key) { if (p->cnt > 0) { p->cnt --; return 0; } } p = p->next; } return -1; } int hash_insert(struct hash_head *db, int key) { int index = get_index(key); struct hashnode *p, *prev; p = db[index].head; if (p == NULL) { struct hashnode *node; node = new_node(key); if (node < 0) { return -1; } db[index].head = node; return 0; } while(p != NULL) { if (p->key == key) { p->cnt ++; return 0; } prev = p; p = p->next; } struct hashnode *node; node = new_node(key); if (node == NULL) { return -1; } prev->next = node; return 0; } /** * Note: The returned array must be malloced, assume caller calls free(). */ int* intersect(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){ struct hash_head *db; db = init(); if (db == NULL) { *returnSize = 0; return NULL; } int len = nums1Size; if (nums1Size > nums2Size) { len = nums2Size; } int *res; res = (int*)malloc(sizeof(int)*len); if (res == NULL) { *returnSize = 0; return NULL; } int i, ret, cnt; for (i = 0; i < nums1Size; i ++) { ret = hash_insert(db, nums1[i]); if (ret < 0) { *returnSize = 0; return NULL; } } cnt = 0; for (i = 0; i < nums2Size; i ++) { ret = hash_search_rec(db, nums2[i]); if (ret == 0) { res[cnt ++] = nums2[i]; } } *returnSize = cnt; return res; } int main() { int nums1[4] = {1, 2, 2, 1}; int nums2[2] = {2, 2}; int *res; int cnt; res = intersect(nums1, 4, nums2, 2, &cnt); printf("%d\n", cnt); int i; for (i = 0; i < cnt; i ++) { printf("%d ", res[i]); } printf("\n"); return 0; }
C
#include <stdio.h> #include <math.h> #include <stdlib.h> int x[30], count = 0; int place(int k, int i) { int j; for (j = 1; j <= k - 1; j++) { if ((x[j] == i) || ((abs(x[j] - i) == abs(j - k)))) return 0; } return 1; } void print_sol(int n) { int i, j; count++; printf("\n\nSolution #%d:\n", count); for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) { if (x[i] == j) printf("Q\t"); else printf("*\t"); } printf("\n"); } } void queen(int k, int n) { int i, val; for (i = 1; i <= n; i++) { if (place(k, i)) { x[k] = i; if (k == n) print_sol(n); else queen(k + 1, n); } } } void main() { int i, n; printf("Enter the number of Queens\n"); scanf("%d", &n); queen(1, n); printf("\nTotal solutions=%d\n", count); }
C
//Marcus Rolim //ALGORITMO SELECTION SORT #include<stdio.h> #include<stdlib.h> #include<time.h> #define MAX 100000 // INDICE DE FUNES void bubbleSort(int *vetor); //FIM INDICE DE FUNES // INCIO DO MAIN int main(){ int vetor[MAX]; bubbleSort(vetor); return 0; } //FIM DO MAIN // ESTRUTURAS DAS FUNES void bubbleSort(int *vetor){ int i, j, MIN, aux; char nomeArquivo[30], opcao; float tempo; FILE *lerArquivo; printf("Caso queira fazer teste, ja existe arquivos modelos: \n\n -> 'aleatorio.txt' \n -> 'ordeminversa.txt' \n -> 'ordenado.txt'\n"); printf("\nDigite o nome do arquivo que deseja organizar: \n"); printf("OBS: O arquivo deve estar no mesmo diretorio do executavel.\n"); printf("-> "); scanf("%s", &nomeArquivo); printf("PROCESSANDO..."); lerArquivo = fopen(nomeArquivo, "r"); for(i = 0 ; i < MAX ; i++){ fscanf(lerArquivo, "%d", &vetor[i]); }//end for lerArquivo = fopen("MarcusRolimBubbleSort.txt", "w"); tempo = clock(); for(i = 1 ; i < MAX ; i++){ for( j = 0; j < (MAX - 1); j++){ if(vetor[j] > vetor[j+1]){ aux = vetor[j]; vetor[j] = vetor[j+1]; vetor[j+1] = aux; }//end if }//end for j } // end for for(i=0; i <= MAX; i++){ fprintf(lerArquivo, "%d ", vetor[i]); } fclose(lerArquivo); tempo = (clock() - tempo)/1000; printf("\nTempo utilizado para odernar foi de %.4f segundos.\n", tempo); printf("\nProcessamento concluido. Arquivo salvo como MarcusRolimBubbleSort.txt\n"); }// end bubbleSort // FIM DAS ESTRUTURAS DAS FUNES
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include "mem_managment.h" void set_rand_num(int **matrix, int size) { srand(time(NULL)); /* Initialization, should only be called once */ for(int i = 0; i < size; i++) { for(int j = 0; j < size; j++) matrix[i][j] = rand() % 10; /* random int between 0 and 10 */ } } void print_matrix(int **matrix, int size) { printf("---------------Matrix---------------\n"); int centralNum = size/2; for(int i = 0; i < size; i++) { for(int j = 0; j < size; j++) { if(matrix[centralNum][centralNum] < 99) printf("%3d", matrix[i][j]); else printf("%5d", matrix[i][j]); } printf("\n"); } } void set_triangles(int **matrix, int size) { int i, j, k; set_zero_values(matrix, size); for(i = 0, k = 0; i < size; i++, k++) { j = k; while(j < size) { matrix[i][j] = 1; j++; } } } void set_helix(int **matrix, int size) { int i = 0, j, k = 0, p = 1; int numCounter = size*size; set_zero_values(matrix, size); while(i < numCounter) { k++; for (j = k-1; j < size-k+1; j++) { matrix[k-1][j] = p++; i++; } for (j = k;j < size-k+1; j++) { matrix[j][size-k] = p++; i++; } for (j = size-k-1; j >= k-1; j--) { matrix[size-k][j] = p++; i++; } for (j = size-k-1; j >= k; j--) { matrix[j][k-1] = p++; i++; } } } int main(int argc, char **argv) { int **matrix = NULL; int size = 0; if(argc < 2) { printf("Usage: %s <quad matrix size>\n", argv[0]); exit(EXIT_FAILURE); } if(!(size = atoi(argv[1]))) { printf("Usage: %s size-integer\n", argv[0]); exit(EXIT_FAILURE); } matrix = mem_calloc(matrix, size); set_rand_num(matrix, size); print_matrix(matrix, size); set_triangles(matrix, size); print_matrix(matrix, size); set_helix(matrix, size); print_matrix(matrix, size); free_mem(matrix, size); return EXIT_SUCCESS; }
C
#ifndef Misc_H #define Misc_H #define debug true #include <Arduino.h> #include <Wire.h> void debug_msg(String msg) { if (debug) { Serial.print("DEBUG ::\t"); Serial.println(msg); } } float toDegree(float radian) { return 57.29578 * radian; } float toRadian(float degree) { return 0.017453 * degree; } float angleDiff(float inp, float set) { float tmp = abs(inp - set); float diff = min(tmp, abs(360 - tmp)); if ((set + diff) != inp && (set - diff) != inp) { if ((inp + diff) >= 360) return -diff; else return diff; } else return (inp - set); } void writeByte(uint8_t address, uint8_t subAddress, uint8_t data) { Wire.beginTransmission(address); Wire.write(subAddress); Wire.write(data); Wire.endTransmission(); } uint8_t readByte(uint8_t address, uint8_t subAddress) { uint8_t data; Wire.beginTransmission(address); Wire.write(subAddress); Wire.endTransmission(); Wire.requestFrom(address, (size_t)1); data = Wire.read(); return data; } void readBytes(uint8_t address, uint8_t subAddress, uint8_t count, uint8_t *dest) { Wire.beginTransmission(address); Wire.write(subAddress); Wire.endTransmission(); uint8_t i = 0; Wire.requestFrom(address, (size_t)count); while (Wire.available()) { dest[i++] = Wire.read(); } } float maxm(float a, float b) { return (a > b) ? a : b; } float maxm(float a, float b, float c) { return maxm(max(a, b), c); } float map2(float val, float low_in, float high_in, float low_op, float high_op) { return (((val - low_in) / (high_in - low_in)) * (high_op - low_op)) + low_op; } #endif
C
#include <stdlib.h> #include "f_header.inc" /* This program edits all .100 data files and generates weather */ /* statistics for placement in the site.100 file */ /* Globals */ FILE *infp, *outfp, *deffp; /* MAIN */ void main() { int answer, done, i; /* Print title and date */ printf("\n DayCent 4.5 File Updating Utility\n"); printf(" 03/01/04\n"); done = FALSE; while (done == FALSE) { printf("\n Enter the number of the file you wish to update:\n"); printf(" 0. quit\n"); for (i = 1; i < NUMTYPES-2; i++) { printf(" %2i. %s.100\n", i, fstr[i]); } printf(" %2i. %s\n", i, fstr[i]); printf(" %2i. %s\n", i+1, fstr[i+1]); printf("\n Enter selection:\n"); answer = getint(); if (answer == QUIT) { done = TRUE; } else if (answer == WTHR) { weather("null","null"); } else if (answer == SOIL) { create_soil(SOIL); } else if (answer < QUIT || answer >= NUMTYPES) { printf(" Invalid response. Please re-enter.\n"); continue; } else { submenu(answer); } } }
C
#define _GNU_SOURCE #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <string.h> #include <assert.h> #include <stdbool.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #define OPEN_OUTPUT (O_RDWR | O_CREAT | O_TRUNC) #define OPEN_INPUT (O_RDONLY) #define FILE_PERMS (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH) /* rw-rw-rw- */ bool allowBackground = true; void print_array(int argc, char *argv[]) { for (int i = 0; i < argc; i++) { fprintf(stdout, "argv[%d] = %s\n", i, argv[i]); fflush(stdout); } } void print_exit_status(int spawnPid, int child_status) { if(WIFEXITED(child_status)) { int lastExit = WEXITSTATUS(child_status); fprintf(stdout, "background pid is %d is done: exit value %d\n", spawnPid, lastExit); fflush(stdout); } else { int signal = WTERMSIG(child_status); fprintf(stdout, "background pid is %d is done: terminated by signal %d\n", spawnPid, signal); fflush(stdout); } } void handle_SIGTSTP(int signo) { char *message; if(allowBackground == true) { allowBackground = false; message = "\nEntering foreground-only mode (& is now ignored)\n: "; write(STDOUT_FILENO, message, 52); fflush(stdout); } else { allowBackground = true; message = "\nExiting foreground-only mode\n: "; write(STDOUT_FILENO, message, 32); fflush(stdout); } } int welcome() { system("clear"); fprintf(stdout, "\nWelcome to:\n"); fprintf(stdout, " _____ _ _ _____ _ _ _\n" "/ ___| | | | / ___| | | | |\n" "\\ `--. _ __ ___ __ _| | | \\ `--.| |__ ___| | |\n" " `--. \\ '_ ` _ \\ / _` | | | `--. \\ '_ \\ / _ \\ | |\n" "/\\__/ / | | | | | (_| | | | /\\__/ / | | | __/ | |\n" "\\____/|_| |_| |_|\\__,_|_|_| \\____/|_| |_|\\___|_|_|\n"); fprintf(stdout, "\nA small, lighter shell similar to Bourne Again SHell!\n\n"); fflush(stdout); } int changeDir(char *argv[]) { if(argv[1] == NULL || strcmp(argv[1], "~") == 0) argv[1] = getenv("HOME"); int status = chdir(argv[1]); switch(status) { case -1: perror("invalid path"); break; default: return 0; } } void redirectInput(char *argv) { int targetFD = open(argv, OPEN_INPUT); if(targetFD == -1) { fprintf(stderr, "cannot open %s for input\n", argv); exit(1); } int input = dup2(targetFD, 0); //redirect stdin to read from targetFD if (input == -1) { perror("source dup2()"); exit(1); } } void redirectOutput(char *argv) { int targetFD = open(argv, OPEN_OUTPUT, FILE_PERMS); if(targetFD == -1) { perror("open()"); exit(1); } int output = dup2(targetFD, 1); //redirect stdout to write to targetFD if (output == -1) { perror("source dup2"); exit(1); } } int execute( char *argv[], bool background, int *signal, int *bg_pids, int *exit_status, struct sigaction *SIGINT_action) { int child_status; int redirect_flag = 0; if(strcmp(argv[0], "cd") == 0 || strcmp(argv[0], "chdir") == 0) { changeDir(argv); } else { pid_t spawnPid = fork(); switch(spawnPid) { // fork() returns -1 if it fails to spawn a new child case -1: perror("fork() failed!"); exit(1); break; // spawn id is 0 in the child process. case 0: // Reset child signal handler for SIGINT to default values. SIGINT_action->sa_handler = SIG_DFL; sigaction(SIGINT, SIGINT_action, NULL); int i = 0; while(argv[i + 1] != NULL) { if(strcmp(argv[i], ">") == 0) { redirectOutput(argv[i + 1]); redirect_flag = 1; } else if(strcmp(argv[i], "<") == 0) { redirectInput(argv[i + 1]); redirect_flag = 1; } i++; } if(redirect_flag) { argv[1] = NULL; // terminate argv[1] for passing to exec } execvp(argv[0], argv); perror(argv[0]); exit(2); break; default: if(background && allowBackground) { waitpid(spawnPid, &child_status, WNOHANG); printf("background pid is %d\n", spawnPid); fflush(stdout); (*bg_pids)++; } else { waitpid(spawnPid, &child_status, 0); if(strcmp(argv[0], "kill") == 0) { //TODO, bad logic, needs to clean up; } else if(WIFEXITED(child_status)) { *exit_status = WEXITSTATUS(child_status); } else { *signal = WTERMSIG(child_status); fprintf(stdout, "terminated by signal %d\n", *signal); } } } } return(0); } int freeMem() { } void expandVars(char **argv) { // get process id for $$ variable expansion. char pid[10], *orig_str; sprintf(pid, "%d", getpid()); int argc = 0; // **** Variable Expansion for $$ into Process ID of Parent **** while (argv[argc] != NULL) { orig_str = argv[argc]; int shift_r = strlen(pid); for(int i = 0; i < strlen(orig_str); i++) { if(orig_str[i] == '$' && orig_str[i+1] == '$') { int len_n = strlen(orig_str) + shift_r - 2; int index_s = i; char expand_str[len_n]; for(int j = 0; j < len_n; j++) { if (j < index_s || j > index_s + shift_r) { expand_str[j] = orig_str[j]; } else { for(int k = 0; k < shift_r; k++) { expand_str[j] = pid[k]; j++; } } } expand_str[len_n] = '\0'; strcpy(orig_str, expand_str); break; } } argc++; } } int getInput(char **argv, bool *background) { size_t nbytes = 2048; char* input = (char *) malloc(sizeof(char) * nbytes); int argc = 0; fprintf(stdout, ": "); fflush(stdout); getline(&input, &nbytes, stdin); // might need to change to newfd strtok(input, "\n"); // strip off newline char from end of user input. argv[argc] = strtok(input, " "); while (argv[argc] != NULL) { argc++; argv[argc] = strtok(NULL, " "); } // check if command should be run in the background and set flag if(strcmp(argv[argc - 1], "&") == 0) { *background = true; //replace it with a NULL value for passing to exec argv[argc - 1] = NULL; } else { // set last char* to NULL for passing to execvp argv[argc] = NULL; } //print_array(argc, argv); free(input); input = NULL; } void statusCmd(int* signal, int *exit_status) { if (signal) { fprintf(stderr, "terminated by signal %d\n", *signal); *signal = 0; //reset signal to false (0) fflush(stderr); } else { fprintf(stderr, "exit value %d\n", *exit_status); fflush(stderr); } } void checkBackgroundPids(int *bgPids) { pid_t pid; int childStatus; // Check for terminated child background processes. while ((pid = waitpid(-1, &childStatus, WNOHANG)) > 0) { if(*bgPids != 0){ print_exit_status(pid, childStatus); fflush(stdout); } (*bgPids)--; } } int run(struct sigaction *SIGINT_action) { int signal = 0, exit_status = 0, argc = 0, arg_size = 64; bool loop = true, background = false; int child_status, bg_pids = 0; pid_t childPid; char** argv = (char ** )malloc(sizeof(char *) * 512); // up to max of 512 arguments. if(argv == NULL){ fprintf(stderr, "insufficient memory available\n"); exit(1); } for(int i = 0; i < 512; i++){ argv[i] = (char *)malloc(sizeof(char) * 64); // each arg max of 64 characters. if(argv == NULL){ fprintf(stderr, "insufficient memory available\n"); exit(1); } } while(loop) { getInput(argv, &background); expandVars(argv); // skip lines with comments or blank lines. if(strcmp(argv[0], "#") == 0 || strcmp(argv[0], "\n") == 0) { // do nothing... } // Exit Command else if (strcmp(argv[0], "exit") == 0) { //TODO needs to check for background processes and kill them. loop = false; } // Status Command else if(strcmp(argv[0], "status") == 0) { statusCmd(&signal, &exit_status); } else // Execute non-built in command by system call. { execute(argv, background, &signal, &bg_pids, &exit_status, SIGINT_action); } checkBackgroundPids(&bg_pids); background = false; } // 0 sends SIGTERM to all processes within parent process group. //TODO freeMem(argv); kill(0, SIGTERM); exit(EXIT_SUCCESS); } int init() { // Redirct ctrl-C to ignore signal in parent process (shell) struct sigaction SIGINT_action = {0}; SIGINT_action.sa_handler = SIG_IGN; sigfillset(&SIGINT_action.sa_mask); SIGINT_action.sa_flags = 0; sigaction(SIGINT, &SIGINT_action, NULL); // Redict ctrl-Z to handle_SIGSTP struct sigaction SIGTSTP_action = {0}; //memset(&SIGTSTP_action, 0, sizeof(SIGTSTP_action)); SIGTSTP_action.sa_handler = handle_SIGTSTP; sigfillset(&SIGTSTP_action.sa_mask); SIGTSTP_action.sa_flags = SA_RESTART; sigaction(SIGTSTP, &SIGTSTP_action, NULL); welcome(); run(&SIGINT_action); }
C
#include <stdio.h> #include <math.h> int main () { int a=0, b=0, A, i=1; scanf("%d", &a); A=a; scanf("%d", &b); for (i=1;i < b;i++) { a += A; } printf("%d\n", a); a = A; i = 1; while (i < b) { a +=A; i++; } printf("%d", a); return 0; }
C
/* * Copyright (c) 1986, 1990 by The Trustees of Columbia University in * the City of New York. Permission is granted to any individual or * institution to use, copy, or redistribute this software so long as it * is not sold for profit, provided this copyright notice is retained. */ /* * program to move file a to file b, obeying file locking. * meant to be suid'ed or sgid'ed. * * The point is to be able to move a user's mail file out of /usr/spool/mail, * to a file of their own. * * Must check accesses of REAL uid, to be sure that the file can be moved. * The user must have read access to the original, and write access to the * destination directory. The destination file must not exist. */ #ifndef lint static char *rcsid = "$Header: /w/src1/sun4.bin/cucca/mm/RCS/movemail.c,v 2.1 90/10/04 18:25:11 melissa Exp $ "; #endif #include "config.h" #include "osfiles.h" #include "compat.h" extern int errno; #define TRUE 1 #define FALSE 0 FILE *infile = NULL; FILE *outfile = NULL; main(argc, argv) int argc; char **argv; { if (argc != 3) { usage(argv[0]); exit(1); } if (readaccess(argv[1]) && /* must be able to read the src */ writeaccess_dir(argv[2]) && /* have write access to the directory*/ /* of the destination file */ !exist(argv[2]) && /* the destination cannot exist */ (locked(argv[1]))) /* and the source cannot be locked */ { return(!movefile(argv[1], argv[2])); /* do it!! */ } else return(1); } usage(pname) char *pname; { fprintf(stderr,"Usage: %s srcfile destfile\n", pname); } /* * check if the real user (no suid/sgid bits considered) is readable */ readaccess(fname) char *fname; { if (access(fname,R_OK)) { perror(fname); return(FALSE); } return(TRUE); } writeaccess_dir(fname) char *fname; { char *cp, *rindex(); char c; cp = rindex(fname,'/'); if (cp) { c = *(++cp); *cp = '\0'; if (access(fname,W_OK) != 0) { perror(fname); return(FALSE); } *cp = c; return(TRUE); } else if (access(".", W_OK) != 0){ perror(fname); return(FALSE); } return(TRUE); } exist(fname) { if (access(fname,F_OK) == 0) { fprintf(stderr,"%s: file exists\n", fname); return(TRUE); } return(FALSE); } locked(fname) char *fname; { char buf[MAXPATHLEN]; infile = fopen(fname,"r"); /* open the input file */ if (infile == NULL) { perror(fname); return(FALSE); } return(lock(infile, fname)); /* and lock it */ } /* * move from "from" to "to" */ movefile(from, to) char *from; char *to; { int c; outfile = fopen(to, "w"); if (outfile == NULL) { /* can't open....stop */ perror(to); unlock(infile,from); /* but unlock the locked file */ return(FALSE); } while((c = getc(infile)) != EOF) /* copy */ if (putc(c,outfile) == EOF) { fclose(outfile); unlink(outfile); unlock(infile,from); return(FALSE); } if (fclose(outfile) == EOF) { /* error flushing */ unlink(outfile); unlock(infile,from); return(FALSE); } if (unlink(from) < 0) { /* unlink the original, */ truncate(from,0); /* or at least truncate it */ } unlock(infile,from); /* unlock the source. */ return(TRUE); } lock(fp, fname) FILE *fp; char *fname; { #ifdef MAIL_USE_FLOCK if (flock(fileno(fp),LOCK_EX|LOCK_NB) < 0) { fprintf(stderr,"%s: already locked\n",fname); return(FALSE); } #else char buf[MAXPATHLEN]; int fd; sprintf(buf,"%s.lock", fname); if ((fd = open(buf,O_CREAT|O_EXCL|O_WRONLY, 0)) < 0) { if (errno == EEXIST) fprintf(stderr,"%s: already locked\n",fname); else perror(buf); return(FALSE); } #endif return(TRUE); } unlock(fp,fname) FILE *fp; char *fname; { #ifdef MAIL_USE_FLOCK flock(fileno(fp),LOCK_EX|LOCK_UN); #else char buf[MAXPATHLEN]; sprintf(buf,"%s.lock", fname); unlink(buf); #endif return(TRUE); }
C
#include "syscall.h" #include "stdio.h" #include "stdlib.h" #define BUFSIZE 1024 #define BUFSIZE2 300 char buf[BUFSIZE]; char buf2[BUFSIZE2]; int main(int argc, char** argv) { testCreatWriteClose(); testOpenClose(); testRead(); exit(0); } <<<<<<< .mine int testCreatWriteClose() { char * fileName = "/Users/willywu/Desktop/newFile.c"; int fileDesc = creat(fileName); if (fileDesc != -1) { printf("You successfully opened the file: %s", fileName); } else { printf("You failed to open %s", fileName); } buf[0] = 'W'; buf[1] = 'i'; buf[2] = 'l'; buf[3] = 'l'; buf[4] = 'y'; buf[5] = '\n'; write(fileDesc, buf, 10); close(fileDesc); return 0; } int testOpenClose() { ======= int testCreatWriteClose() { char * fileName = "newFile.c"; int fileDesc = creat(fileName); if (fileDesc != -1) { printf("You successfully opened the file: %s", fileName); } else { printf("You failed to open %s", fileName); } buf[0] = 'W'; buf[1] = 'i'; buf[2] = 'l'; buf[3] = 'l'; buf[4] = 'y'; buf[5] = '\n'; write(fileDesc, buf, 10); close(fileDesc); return 0; } int testOpenClose() { >>>>>>> .r119 char * fileName = "cat.c"; int fileDesc = open(fileName); if (fileDesc != -1) { printf("You successfully opened the file: %s", fileName); } else { printf("You failed to open %s", fileName); } close(fileDesc); return 0; } int testRead() { char * fileName = "cat.c"; int fileDesc = open(fileName); int bytesRead = read(fileDesc, buf, 20); bytesRead = read(fileDesc, buf, 100); bytesRead = read(fileDesc, buf, 0x800); close(fileDesc); return 0; }
C
//Strong no is a number in which sum of factorial of individual digits is equal to the number #include<stdio.h> void strong(int n) { int fact=1,i,sum=0,j; for(i) for(j=1;j<=n;j++) { fact=fact*i } } int main() { int a; printf("Enter no. :"); scanf("%d",&a); strong(a) }
C
#include <stdlib.h> #include <stdio.h> #include "task.h" #include "schedulers.h" #include "list.h" #include "cpu.h" struct node *head = NULL, *tail = NULL; int size = 0; void add(char *name, int priority, int burst) { Task *temp = malloc(sizeof(struct node)); temp->name = name; temp->priority = priority; temp->burst = burst; // if empty, set head if (size == 0) { insert(&head, temp); } // if task is alphabetically before head, replace head and shift old head else if (comesBefore(temp->name, head->task->name)) { insert(&head, temp); } // insertion sort else { struct node *curr = head->next, *prev = head, *newNode; // traverse list until insertion point found while (curr != NULL && comesBefore(curr->task->name, temp->name)) { prev = curr; curr = curr->next; } // insert before current node newNode = insert(&curr, temp); prev->next = newNode; } size++; } void schedule() { struct node *temp = head; // while not empty while (size > 0) { Task *task = temp->task; // if task's burst time greater than quantum if (task->burst > QUANTUM) { run(task, QUANTUM); // run for quantum task->burst -= QUANTUM; // calculate remaining burst time temp = temp->next; } // otherwise run for remaining burst and remove task else { run(task, task->burst); temp = temp->next; delete(&head, task); size--; } // if end of list if (temp == NULL) { temp = head; // go back to head } } }
C
/*one-pass algorithm to calculate the covariance*/ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> /* x -- the variable which is to calculate it's variance length -- the length of the x, it is int var -- the variance of x that we need, it is double mx -- mean of x my -- mean of y mxprev -- mx(mean of x) previous value myprev --my(mean of y) previous value */ void mycov(double *x, double *y, int *length, double *cov, double *meanx, double *meany) { int N = *length, i; double C = 0,mx = 0, my = 0, mxprev = 0, myprev = 0; /* Cprev means the previous value of C */ for ( i = 0; i < N; i++) { mxprev = mx; myprev = my; mx += (x[i] - mxprev)/(i+1); my += (y[i] - myprev)/(i+1); C += (x[i] - mx)*(y[i] - myprev); } *cov = C/(N-1); *meanx = mx; *meany = my; }
C
#include <stdio.h> #include <setjmp.h> #include <sched.h> #define JUMP_PARENT 0x00 #define JUMP_CHILD 0xA0 #define JUMP_INIT 0xA1 struct clone_t { char stack[4096] __attribute__((aligned(16))); char stack_ptr[0]; jmp_buf *env; int jmpval; }; static int child_func(void *arg) __attribute__ ((noinline)); static int child_func(void *arg) { struct clone_t *ca = (struct clone_t*)arg; // 通过longjmp跳转到合适的位置,ca->jmpval就是setjmp的返回值 longjmp(*ca->env, ca->jmpval); } static int clone_parent(jmp_buf *env, int jmpval) __attribute__ ((noinline)); static int clone_parent(jmp_buf *env, int jmpval) { struct clone_t ca = { .env = env, .jmpval = jmpval, }; return clone(child_func, ca.stack_ptr, 0, &ca); } int main(int argc, char **argv) { jmp_buf env; // 保存stack context/environment到env中,该env变量后续会被函数longjmp作为参数使用 // setjmp会直接返回0,如果从longjmp返回,返回值为longjmp的第二个参数的值。 switch (setjmp(env)) { case JUMP_PARENT: printf("parent: pid = %d, ppid = %d\n", getpid(), getppid()); clone_parent(&env, JUMP_CHILD); sleep(3); break; case JUMP_CHILD: printf("child: pid = %d, ppid = %d\n", getpid(), getppid()); clone_parent(&env, JUMP_INIT); sleep(1); break; case JUMP_INIT: printf("init: pid = %d, ppid = %d\n", getpid(), getppid()); break; default: break; } }
C
#include "termhdr.h" /* ** Set input file descriptor and type-ahead descriptor. ** If fd < 0, only the type-ahead descriptor is set. ** ** Written by Kiem-Phong Vo */ #if __STD_C int typeahead(int fd) #else int typeahead(fd) int fd; #endif { if(fd < 0) _ahead = fd; else tinputfd(fd); return OK; }
C
#include <stdlib.h> #include <stdio.h> #include "dado.h" #include <assert.h> /* Gera $l$ observaes de acordo com o modelo $(a, e)$. A matriz de transio de estados $a$ possui dimenses $N \times N$. A matriz de emisso de smbolos $e$ possui dimenses $N \times M$. A funo imprime uma seqncia de $l$ observaes de acordo com o modelo da entrada. Supe-se que o conjunto de estados $Q = \{0, \ldots, N-1\}$ e que o estado inicial o estado $0$ (que no gera smbolos). Supe-se que o alfabeto seja $\Sigma = \{0, \ldots, M-1 \}$. */ void observa(double **a, double **e, int N, int M, int l) { int t = 0; /* nmero de caracteres gerados */ int q = 0; /* estado atual do modelo */ for (t = 0; t < l; t++) { q = dado(a[q], N); printf("(%d, %d)\n", q, dado(e[q], M)); } } /* TODO: implementar HMMs como objetos? */ /* Recebe um arquivo j aberto e l desse arquivo os parmetros de um modelo de Markov de estados ocultos. O arquivo deve estar no formato: N M matriz de transies matriz de emisses */ void lemodelo(FILE *f, double ***a, double ***e, int *N, int *M) { int i, j; /* erros nao sao verificados */ fscanf(f, "%d %d", N, M); *a = malloc(*N * sizeof(double *)); for (i = 0; i < *N; i++) { (*a)[i] = malloc(*N * sizeof(double)); } *e = malloc(*N * sizeof(double *)); for (i = 0; i < *N; i++) { (*e)[i] = malloc(*M * sizeof(double)); } fscanf(f, "\n"); /* desnecessrio? */ /* matrizes alocadas, agora leitura */ for (i = 0; i < *N; i++) { for (j = 0; j < *N; j++) { fscanf(f, "%lf", &((*a)[i][j])); } } fscanf(f, "\n"); /* idem */ for (i = 0; i < *N; i++) { for (j = 0; j < *M; j++) { fscanf(f, "%lf", &((*e)[i][j])); } } } void imprimemodelo(double **a, double **e, int N, int M) { int i, j; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) printf("%f ", a[i][j]); printf("\n"); } printf("\n"); for (i = 0; i < N; i++) { for (j = 0; j < M; j++) printf("%f ", e[i][j]); printf("\n"); } printf("\n"); } int main(int argc, char *argv[]) { int N, M, l; FILE *f; double **a, **e; if (argc != 2) { printf("%s: Uso:\n" "\t%s <num>,\n" "onde <num> e o comprimento da observacao a ser gerada.\n", argv[0], argv[0]); exit(1); } f = fopen("hmm.txt", "r"); lemodelo(f, &a, &e, &N, &M); fclose(f); imprimemodelo(a, e, N, M); l = atoi(argv[1]); observa(a, e, N, M, l); return 0; }
C
#include <math.h> #include <stdio.h> int main(){ double x1; double x2; double x3; if(-15.0 <= x1 && x1 <= 15 && -15.0 <= x2 && x2 <= 15.0 && -15.0 <= x3 && x3 <= 15) { double res=2*x1*x2*x3 + 3*x3*x3 - x2*x1*x2*x3 + 3*x3*x3 - x2; if(-56010.0001 >= res || res >= 58740.0) printf("Solved 75"); } return 0; }
C
/******************************************************************* * Filename: parcer.c * PURPOSE: * Recursive Descent Predictive Parser (RDPP) for the PLATYPUS 2.0 language. * CST8152, Assignment #3 * * * Created by: Frederic Desjardins * Student#: 040941359 * Date: December 13th 2020 * */ #include "parser.h" #define debugMode 0 Token lookahead; /************************************************************* * Process Parser ************************************************************/ void processParser(void) { if (debugMode) fprintf(stderr, "[00] Processing parser...\n"); lookahead = processToken(); program(); matchToken(SEOF_T, NO_ATTR); printf("%s\n", "PLATY: Source file parsed"); } /************************************************************* * Match Token ************************************************************/ void matchToken(int tokenCode, int tokenAttribute) { int matchFlag = 1; switch (lookahead.code) { case KW_T: case REL_OP_T: case ART_OP_T: case LOG_OP_T: // TODO_05 if (tokenAttribute != lookahead.attribute.get_int) { syncErrorHandler(tokenCode); return; } else { break; } default: //TO if (lookahead.code == tokenCode) { matchFlag = 1; } else { matchFlag = 0; } break; } if (matchFlag && lookahead.code == SEOF_T) { // TODO_07 return; } if (matchFlag) { // TODO_08 lookahead = processToken(); if (lookahead.code == ERR_T) { printError(); lookahead = processToken(); syntaxErrorNumber++; return; } } else { //TODO_09 syncErrorHandler(tokenCode); return; } } /************************************************************* * Syncronize Error Handler ************************************************************/ void syncErrorHandler(int syncTokenCode) { // TODO_10 printError(); syntaxErrorNumber++; while (lookahead.code != syncTokenCode) { // TODO_11 lookahead = processToken(); if (lookahead.code == SEOF_T) { if (syncTokenCode != SEOF_T) { exit(syntaxErrorNumber); } else { return; } } } if (lookahead.code != SEOF_T) { // TODO_12 lookahead = processToken(); } return; } /************************************************************* * Print Error ************************************************************/ void printError() { Token t = lookahead; if (debugMode) fprintf(stderr, "[39] PrintError\n"); printf("PLATY: Syntax error: Line:%3d\n", line); printf("***** Token code:%3d Attribute: ", t.code); switch (t.code) { // TODO_13 case ERR_T: /* -1 Error token */ printf("%s\n", t.attribute.err_lex); break; case SEOF_T: /* 0 Source end-of-file token */ printf("SEOF_T\t\t%d\t\n", t.attribute.seof); break; case AVID_T: /* 1 Arithmetic Variable identifier token */ case SVID_T:/* 2 String Variable identifier token */ printf("%s\n", t.attribute.vid_lex); break; case FPL_T: /* 3 Floating point literal token */ printf("%5.1f\n", t.attribute.flt_value); break; case INL_T: /* 4 Integer literal token */ printf("%d\n", t.attribute.get_int); break; case STR_T:/* 5 String literal token */ printf("%s\n", bufferGetString(stringLiteralTable, t.attribute.str_offset)); break; case SCC_OP_T: /* 6 String concatenation operator token */ printf("NA\n"); break; case ASS_OP_T:/* 7 Assignment operator token */ printf("NA\n"); break; case ART_OP_T:/* 8 Arithmetic operator token */ printf("%d\n", t.attribute.get_int); break; case REL_OP_T: /* 9 Relational operator token */ printf("%d\n", t.attribute.get_int); break; case LOG_OP_T:/*10 Logical operator token */ printf("%d\n", t.attribute.get_int); break; case LPR_T: /*11 Left parenthesis token */ printf("NA\n"); break; case RPR_T: /*12 Right parenthesis token */ printf("NA\n"); break; case LBR_T: /* 13 Left brace token */ printf("NA\n"); break; case RBR_T: /* 14 Right brace token */ printf("NA\n"); break; case KW_T: /* 15 Keyword token */ printf("%s\n", keywordTable[t.attribute.get_int]); break; case COM_T: /* 16 Comma token */ printf("NA\n"); break; case EOS_T: /* 17 End of statement (;) */ printf("NA\n"); break; case RTE_T: /* 18 Run time error token */ printf("NA\n"); break; default: printf("PLATY: Scanner error: invalid token code: %d\n", t.code); } } /************************************************************* * Program statement * BNF: <program> -> PLATYPUS { <opt_statements> } * FIRST(<program>)= {KW_T (PLATYPUS)}. ************************************************************/ void program(void) { if (debugMode) fprintf(stderr, "[01] Program\n"); matchToken(KW_T, PROGRAM); matchToken(LBR_T, NO_ATTR); opt_statements(); matchToken(RBR_T, NO_ATTR); printf("%s\n", "PLATY: Program parsed"); } /************************************************************* * Optional statements * <opt_statements> -> <statements> | e * FIRST(<opt_statements>) = {AVID_T, SVID_T, KW_T(IF), KW_T(WHILE), KW_T(INPUT), KW_T(OUTPUT),e } ************************************************************/ void opt_statements(void) { switch (lookahead.code) { case AVID_T: case SVID_T: statements(); break; case KW_T: if (lookahead.attribute.get_int == IF || lookahead.attribute.get_int == WHILE || lookahead.attribute.get_int == INPUT || lookahead.attribute.get_int == OUTPUT) { statements(); break; } default: printf("PLATY: Opt_statements parsed\n"); } } /************************************************************* * Statements * <statements> -> <statement> <statementPrime> ************************************************************/ void statements(void) { statement(); statements_prime(); } /************************************************************* * Statement * <statement> -> <assignment statement> | <selection statement> | <iteration statement> | <input statement> | <output statement> * FIRST (<statement>) = {AVID_T, SVID_T, KW_T(IF), KW_T(WHILE), KW_T(INPUT), KW_T(OUTPUT)} ************************************************************/ void statement(void) { switch (lookahead.code) { case AVID_T: case SVID_T: assignment_statement(); break; case KW_T: switch (lookahead.attribute.get_int) { case IF: selection_statement(); break; case WHILE: iteration_statement(); break; case INPUT: input_statement(); break; case OUTPUT: output_statement(); break; } break; default: printError(); break; } } /************************************************************* * Statement * FIRST (<statementPrime>) = {AVID_T, SVID_T, KW_T(IF), KW_T(WHILE), KW_T(INPUT), KW_T(OUTPUT),e } ************************************************************/ void statements_prime(void) { switch (lookahead.code) { case AVID_T: case SVID_T: statements(); break; case KW_T: if (lookahead.attribute.get_int == IF || lookahead.attribute.get_int == WHILE || lookahead.attribute.get_int == INPUT || lookahead.attribute.get_int == OUTPUT) { statement(); statements_prime(); break; } else { break; } } } /************************************************************* * Assignment statement * <assignment statement> -> <assignment expression> * FIRST (<assignment statement>) = {AVID_T, SVID_T} ************************************************************/ void assignment_statement(void) { assignment_expression(); matchToken(EOS_T, NO_ATTR); printf("PLATY: Assignment statement parsed\n"); } /************************************************************* * Assignment expression * <assignment expression> -> AVID = <arithmetic expression> | SVID = <string expression> * FIRST (<assignment expression>) = {AVID_T, SVID_T} ************************************************************/ void assignment_expression(void) { switch (lookahead.code) { case AVID_T: matchToken(AVID_T, NO_ATTR); /*call match to advance lookahead*/ matchToken(ASS_OP_T, EQ); arithmetic_expression(); printf("PLATY: Assignment expression (arithmetic) parsed\n"); break; case SVID_T: matchToken(SVID_T, NO_ATTR); matchToken(ASS_OP_T, EQ); string_expression(); printf("PLATY: Assignment expression (string) parsed\n"); break; default: printError(); break; } } /************************************************************* * Selection statement * <selection statement> -> if <pre-condition> (<conditional expression>) THEN {<opt_statements>} ELSE {<opt_statements>}; * FIRST (<selection statement>) = {KW_T(IF)} ************************************************************/ void selection_statement(void) { matchToken(KW_T, IF); pre_condition(); matchToken(LPR_T, NO_ATTR); conditional_expression(); matchToken(RPR_T, NO_ATTR); matchToken(KW_T, THEN); matchToken(LBR_T, NO_ATTR); opt_statements(); matchToken(RBR_T, NO_ATTR); matchToken(KW_T, ELSE); matchToken(LBR_T, NO_ATTR); opt_statements(); matchToken(RBR_T, NO_ATTR); matchToken(EOS_T, NO_ATTR); printf("PLATY: Selection statement parsed\n"); } /************************************************************* * Iteration statement * <iteration statement> -> WHILE <pre-condition> (<conditional expression>) DO {<statements>} * FIRST (<iteration statement>) = {KW_T(WHILE)} ************************************************************/ void iteration_statement(void) { matchToken(KW_T, WHILE); pre_condition(); matchToken(LPR_T, NO_ATTR); conditional_expression(); matchToken(RPR_T, NO_ATTR); matchToken(KW_T, DO); matchToken(LBR_T, NO_ATTR); statements(); matchToken(RBR_T, NO_ATTR); matchToken(EOS_T, NO_ATTR); printf("PLATY: Iteration statement parsed\n"); } /************************************************************* * Pre condition * <pre-condition> -> TRUE | FALSE * FIRST (<pre-condition>) = {KW_T(TRUE), KW_T(FALSE)} ************************************************************/ void pre_condition(void) { switch (lookahead.code) { case KW_T: switch (lookahead.attribute.get_int) { case TRUE: matchToken(KW_T, TRUE); break; case FALSE: matchToken(KW_T, FALSE); break; default: printError(); break; } break; default: printError(); break; } } /************************************************************* * Input statement * <input statement> -> INPUT (<variable list>); ************************************************************/ void input_statement(void) { matchToken(KW_T, INPUT); matchToken(LPR_T, NO_ATTR); variable_list(); matchToken(RPR_T, NO_ATTR); matchToken(EOS_T, NO_ATTR); printf("PLATY: Input statement parsed\n"); } /************************************************************* * Variable List * <variable list> -> <variable identifier> <variable list prime> * FIRST (<variable list>) = {AVID_T, SVID_T} ************************************************************/ void variable_list(void) { variable_identifier(); variable_list_prime(); printf("PLATY: Variable list parsed\n"); } /************************************************************* * Variable List Prime * FIRST (<variable list prime >) = {COM_T, e} ************************************************************/ void variable_list_prime(void) { switch (lookahead.code) { case COM_T: matchToken(COM_T, NO_ATTR); variable_identifier(); variable_list_prime(); break; } } /************************************************************* * Variable identifier * <variable identifier> -> AVID | SVID * FIRST (<variable identifier>) = {AVID_T, SVID_T} ************************************************************/ void variable_identifier(void) { switch (lookahead.code) { case AVID_T: case SVID_T: matchToken(lookahead.code, NO_ATTR); break; default: printError(); break; } } /************************************************************* * Output statement * <output statement> -> OUTPUT (<output statementPrime>); ************************************************************/ void output_statement(void) { matchToken(KW_T, OUTPUT); matchToken(LPR_T, NO_ATTR); output_statement_prime(); matchToken(RPR_T, NO_ATTR); matchToken(EOS_T, NO_ATTR); printf("PLATY: Output statement parsed\n"); } /************************************************************* * Output variable list * <output statement Prime> -> <opt_variable list> | STR_T * FIRST (<opt_variable list >) = {AVID_T, SVID_T, STR_T, e} ************************************************************/ void output_statement_prime(void) { switch (lookahead.code) { case AVID_T: case SVID_T: variable_list(); break; case STR_T: matchToken(STR_T, NO_ATTR); printf("PLATY: Output list (string literal) parsed\n"); break; default: printf("PLATY: Output list (empty) parsed\n"); break; } } /************************************************************* * Arithmetic expression * <arithmetic expression> -> <unary arithmetic expression> | <additive arithmetic expression> * FIRST (<arithmetic expression>) = {-, +, AVID_T, FPL_T, INT_L} ************************************************************/ void arithmetic_expression(void) { switch (lookahead.code) { case ART_OP_T: switch (lookahead.attribute.arr_op) { case ADD: case SUB: unary_arithmetic_expression(); break; default: printError(); break; } break; case AVID_T: case FPL_T: case INL_T: case LPR_T: additive_arithmetic_expression(); break; default: printError(); break; } printf("PLATY: Arithmetic expression parsed\n"); } /************************************************************* * Unary arithmetic expression * <unary arithmetic expression> -> - <primary arithmetic expression> | + < primary arithmetic expression> * FIRST (<unary arithmetic expression>) = {-, +} ************************************************************/ void unary_arithmetic_expression(void) { switch(lookahead.code) { case ART_OP_T: switch (lookahead.attribute.arr_op) { case ADD: matchToken(ART_OP_T, ADD); primary_arithmetic_expression(); break; case SUB: matchToken(ART_OP_T, SUB); primary_arithmetic_expression(); break; default: printError(); break; } } printf("PLATY: Unary arithmetic expression parsed\n"); } /************************************************************* * additive arithmetic expression * <additive arithmetic expression> -> + <multiplicative arithmetic expression> <additive arithmetic expression prime> * FIRST (<additive arithmetic expression>) = {AVID_T, FPL_T, INT_L, (} ************************************************************/ void additive_arithmetic_expression(void) { multiplicative_arithmetic_expression(); additive_arithmetic_expression_prime(); } /************************************************************* * additive arithmetic expression prime * <additive arithmetic expression prime> -> + <multiplicative arithmetic expression><additive arithmetic expression prime> | * - <multiplicative arithmetic expression><additive arithmetic expression prime> | e * FIRST (<additive arithmetic expression prime>) = {+, -, e} ************************************************************/ void additive_arithmetic_expression_prime(void) { switch (lookahead.code) { case ART_OP_T: switch (lookahead.attribute.arr_op) { case ADD: case SUB: matchToken(ART_OP_T, lookahead.attribute.arr_op); multiplicative_arithmetic_expression(); additive_arithmetic_expression_prime(); printf("PLATY: Additive arithmetic expression parsed\n"); break; default: break; } } } /************************************************************* * multiplicative arithmetic expression * <multiplicative arithmetic expression> -> <primary arithmetic expression> <multiplicative arithmetic expression prime> * FIRST (<multiplicative arithmetic expression>) = {AVID_T, FPL_T, INT_L, (} ************************************************************/ void multiplicative_arithmetic_expression(void) { primary_arithmetic_expression(); multiplicative_arithmetic_expression_prime(); } /************************************************************* * multiplicative arithmetic expression prime * <multiplicative arithmetic expression prime> -> * <primary arithmetic expression> <multiplicative arithmetic expression prime> | / <primary arithmetic expression> <multiplicative arithmetic expression prime> | e * FIRST (<multiplicative arithmetic expression>) = {*, /, e} ************************************************************/ void multiplicative_arithmetic_expression_prime(void) { switch (lookahead.code) { case ART_OP_T: switch (lookahead.attribute.arr_op) { case MUL: case DIV: matchToken(ART_OP_T, lookahead.attribute.arr_op); primary_arithmetic_expression(); multiplicative_arithmetic_expression_prime(); printf("PLATY: Multiplicative arithmetic expression parsed\n"); break; default: break; } } } /************************************************************* * primary arithmetic expression * <primary arithmetic expression> -> AVID_T | FPL_T | INL_T | (<arithmetic expression>) * FIRST (<primary arithmetic expression>) = {AVID_T, FPL_T, INT_L, (} ************************************************************/ void primary_arithmetic_expression(void) { switch (lookahead.code) { case AVID_T: case FPL_T: case INL_T: matchToken(lookahead.code, NO_ATTR); break; case LPR_T: matchToken(LPR_T, NO_ATTR); arithmetic_expression(); matchToken(RPR_T, NO_ATTR); break; default: printError(); break; } printf("PLATY: Primary arithmetic expression parsed\n"); } /************************************************************* * string expression * <string expression> -> <primary string expression> <string expression prime> * FIRST (<string expression >) = {SVID_T, STR_T} ************************************************************/ void string_expression(void) { primary_string_expression(); string_expression_prime(); printf("PLATY: String expression parsed\n"); } /************************************************************* * string expression prime * <string expression prime> -> $$ <primary string expression> <string expression prime> | e * FIRST (<string expression prime>) = {$$, e} ************************************************************/ void string_expression_prime(void) { switch (lookahead.code) { case SCC_OP_T: matchToken(SCC_OP_T, NO_ATTR); primary_string_expression(); string_expression_prime(); break; default: break; } } /************************************************************* * primary string expression * <primary string expression> -> SVID_T | STR_T * FIRST (<primary string expression>) = {SVID_T, STR_T} ************************************************************/ void primary_string_expression(void) { switch (lookahead.code) { case SVID_T: case STR_T: matchToken(lookahead.code, NO_ATTR); break; default: printError(); break; } printf("PLATY: Primary string expression parsed\n"); } /************************************************************* * conditional expression * <conditional expression> -> <logical OR expression> * FIRST (<conditional expression >) = {AVID_T, SVID_T, INL_T, FPL_T, STR_T} ************************************************************/ void conditional_expression(void) { logical_OR_expression(); printf("PLATY: Conditional expression parsed\n"); } /************************************************************* * logical Or expression * <logical OR expression> -> <logical AND expression> <logical OR expression prime> * FIRST (<logical OR expression>) = {AVID_T, SVID_T, INL_T, FPL_T, STR_T} ************************************************************/ void logical_OR_expression(void) { logical_AND_expression(); logical_OR_expression_prime(); } /************************************************************* * logical Or expression prime * <logical OR expression prime> -> _OR_ <logical AND expression> <logical OR expression prime> | e * FIRST (<logical OR expression prime>) = {_OR_, e} ************************************************************/ void logical_OR_expression_prime(void) { switch (lookahead.code) { case LOG_OP_T: switch (lookahead.attribute.log_op) { case OR: matchToken(LOG_OP_T, OR); logical_AND_expression(); logical_OR_expression_prime(); printf("PLATY: Logical OR expression parsed\n"); break; } break; } } /************************************************************* * logical AND expression * <logical AND expression> -> <logical NOT expression> <logical AND expression prime> * FIRST (<logical AND expression>) = {AVID_T, SVID_T, INL_T, FPL_T, STR_T} ************************************************************/ void logical_AND_expression(void) { relational_expression(); logical_AND_expression_prime(); } /************************************************************* * logical AND expression prime * <logical AND expression prime> -> _AND_ <logical NOT expression> <logical AND expression prime> | e * FIRST (<logical AND expression prime>) = {_AND_, e} ************************************************************/ void logical_AND_expression_prime(void) { switch (lookahead.code) { case LOG_OP_T: switch (lookahead.attribute.log_op) { case AND: matchToken(LOG_OP_T, AND); logical_NOT_expression(); logical_AND_expression_prime(); printf("PLATY: Logical AND expression parsed\n"); break; } break; } } /************************************************************* * logical NOT expression prime * <logical NOT expression> -> _NOT_ <relational expression> | <relational expression> * FIRST (<logical NOT expression>) = {_NOT_, e} ************************************************************/ void logical_NOT_expression(void) { switch (lookahead.code) { case LOG_OP_T: switch (lookahead.attribute.log_op) { case NOT: matchToken(LOG_OP_T, NOT); relational_expression(); printf("PLATY: Logical NOT expression parsed\n"); break; } break; default: relational_expression(); break; } } /************************************************************* * relational expression * <relational expression> -> <primary a_relational expression> <primary a_relational expression prime> | <primary s_relational expression><primary s_relational expression prime> * FIRST (<relational expression>) = {AVID_T, SVID_T, INL_T, FPL_T, STR_T} ************************************************************/ void relational_expression(void) { switch (lookahead.code) { case AVID_T: case FPL_T: case INL_T: primary_a_relational_expression(); primary_a_relational_expression_prime(); break; case SVID_T: case STR_T: primary_s_relational_expression(); primary_s_relational_expression_prime(); break; default: printError(); break; } printf("PLATY: Relational expression parsed\n"); } /************************************************************* * primary a relational expression * <primary a_relational expression> -> AVID_T | FPL_T | INL_T * FIRST (<primary a _relational expression>) = {AVID_T, INL_T, FPL_T} ************************************************************/ void primary_a_relational_expression(void) { switch (lookahead.code) { case AVID_T: case FPL_T: case INL_T: matchToken(lookahead.code, NO_ATTR); break; default: printError(); break; } printf("PLATY: Primary a_relational expression parsed\n"); } /************************************************************* * primary a relational expression prime * <primary a_relational expression prime> -> == <primary a_relational expression>| <> <primary a_relational expression> | > <primary a_relational expression> | < <primary a_relational expression> * FIRST (<primary a_relational expression prime>) = {==, <>, >, <} ************************************************************/ void primary_a_relational_expression_prime(void) { switch (lookahead.code) { case REL_OP_T: switch (lookahead.attribute.rel_op) { case EQ: case NE: case GT: case LT: matchToken(REL_OP_T, lookahead.attribute.rel_op); primary_a_relational_expression(); break; default: printError(); break; } break; default: printError(); break; } } /************************************************************* * primary s relational expression * <primary s_relational expression> -> <primary string expression> * FIRST (<primary s _relational expression>) = {SVID_T, STR_T} ************************************************************/ void primary_s_relational_expression(void) { primary_string_expression(); printf("PLATY: Primary s_relational expression parsed\n"); } /************************************************************* * primary s relational expression prime * <primary s_relational expression prime> -> == <primary s _relational expression>| <> <primary s _relational expression> | > <primary s _relational expression> | < <primary s _relational expression> * FFIRST (<primary s_relational expression prime>) = {==, <>, >, <} ************************************************************/ void primary_s_relational_expression_prime(void) { switch (lookahead.code) { case REL_OP_T: switch (lookahead.attribute.rel_op) { case EQ: case NE: case GT: case LT: matchToken(REL_OP_T, lookahead.attribute.rel_op); primary_s_relational_expression(); break; default: printError(); break; } break; default: printError(); break; } }
C
/** @file * Udostępnia funkcje wypisującą kolorową planszę */ #ifndef ENHANCED_PRINT #define ENHANCED_PRINT #include <stdlib.h> #include "basic_manipulations.h" /** @brief Wypisuje planszę do gry gamma z autorsko pokolorowanymi polami * Wypisuje planszę kolorując pola na które gracz @p player może wykonać złoty ruch, * na inny kolor koloruje pola gracza @p player, a na jeszcze inny pola na które gracz * @p player może się ruszyć zwykłym ruchem. * @param[in,out] g – poprawny wskaźnik na strukturę przechowującą stan gry, * @param[in] player – poprawny numer gracza, którego ruch jest teraz oczekiwany. */ extern void print_enhanced_board(gamma_t *g, uint32_t player); /** Zwaraca pionek gracza * @param[in] player – poprawny numer gracza. * @return Zwraca znak, którym oznaczane będą pola gracz @p player w trybie interaktywnym. */ extern char player_character(uint32_t player); /** Sprawdza czy można wykonać złoty ruch na pole * @param[in] g – poprawny wskaźnik na strukturę przechowującą stan gry, * @param[in] player – poprawny numer gracza, * @param[in] x – poprawny numer kolumny, * @param[in] y – poprawny numer wiersza, * @return Zwraca true jeśli gracz @p player możw wykonać ruch na pole @p x, @p y, false wpp. */ extern bool golden_possible_to_field(gamma_t *g, uint32_t player, uint32_t x, uint32_t y); /** Liczy na ile obszarów rozpadnie się obszar * @param[in] g – poprawny wskaźnik na strukturę przechowującą stan gry, * @param[in] owner – poprawny numer gracza - właściciela pola @p x, @p y. * @param[in] x – poprawny numer kolumny, * @param[in] y – poprawny numer wiersza, * @param[in] pos – indeks pola @p x, @p y. * @return liczba obszarów które powstaną z obszaru do którego należy pole @p x, @p y * po usunięciu pola @p x, @p y. */ extern uint16_t crumbles_to(gamma_t *g, uint32_t owner, uint32_t x, uint32_t y, uint64_t pos); #endif
C
/* Author: hutterj Date: 2017.02.07 File: unittest1.c Purpose: Perform unit tests of function buyCard in dominion.c Rules of buyCard: supplyPos must be valid (be within game spec) cannot buy if less than one buy available cannot buy if no cards in specified supply pile left cannot buy is card's price is more than coins available after a successful buy: that card is present on top of discard all players' decks same as before player's discard is +1 from before supply count is descremented 1 for bought card, same for other cards all players' hand same as before card cost subtracted from coins available buys decremented by 1 */ #include "dominion.h" #include "dominion_helpers.h" #include <string.h> #include <stdio.h> #include <assert.h> #include <stdlib.h> /* Name: asserttrue Purpose: use something like assert to check conditions but still be able to collect coverage */ void asserttrue(int condition, char* condName){ if (condition){ printf("Test: %-33s success.\n", condName); } else { printf("Test: %-33s FAIL.\n", condName); } return; } int main(void){ int seed = 1000; int numPlayers = 2; int thisPlayer = 0; int funcStatus; int i; struct gameState G, testG; int k[10] = {adventurer, embargo, village, minion, mine, cutpurse, sea_hag, tribute, smithy, council_room}; // initialize a game state and player cards initializeGame(numPlayers, k, seed, &G); printf("----------------- Testing Function: buyCard ----------------\n"); // ----------- TEST 1: attempt to buy with negative supplyPos -------------- printf("TEST 1: out of bounds supplyPos\n"); // card is -100 // set coins and buys to make sure we're testing the supplyPos G.coins = 10; G.numBuys = 1; funcStatus = buyCard(-100, &G); asserttrue((funcStatus == -1), "out of bounds supplyPos -100"); // card is -28 // set coins and buys to make sure we're testing the supplyPos G.coins = 10; G.numBuys = 1; funcStatus = buyCard(-28, &G); asserttrue((funcStatus == -1), "out of bounds supplyPos -28"); // card is 999 // set coins and buys to make sure we're testing the supplyPos G.coins = 10; G.numBuys = 1; funcStatus = buyCard(999, &G); asserttrue((funcStatus == -1), "out of bounds supplyPos 999"); // card is 27 // set coins and buys to make sure we're testing the supplyPos G.coins = 10; G.numBuys = 1; funcStatus = buyCard(27, &G); asserttrue((funcStatus == -1), "out of bounds supplyPos 27"); // ----------- TEST 2: attempt to buy with 0 buys -------------- printf("\n\nTEST 2: numBuys 0 or less\n"); initializeGame(numPlayers, k, seed, &G); G.numBuys = 0; funcStatus = buyCard(0, &G); asserttrue((funcStatus == -1), "numBuys 0"); // negative numBuys G.numBuys = -1; funcStatus = buyCard(curse, &G); asserttrue((funcStatus == -1), "numBuys -1"); G.numBuys = -1000; funcStatus = buyCard(curse, &G); asserttrue((funcStatus == -1), "numBuys -1000"); // ----------- TEST 3: supply pile empty -------------- printf("\n\nTEST 3: supply pile 0 or less\n"); initializeGame(numPlayers, k, seed, &G); G.coins = 10; G.numBuys = 1; // no more curses left G.supplyCount[curse] = 0; funcStatus = buyCard(curse, &G); asserttrue((funcStatus == -1), " 0 curses left"); // no more curses left initializeGame(numPlayers, k, seed, &G); G.coins = 10; G.numBuys = 1; G.supplyCount[curse] = -1; funcStatus = buyCard(curse, &G); asserttrue((funcStatus == -1), "-1 curses left"); // no more minions left initializeGame(numPlayers, k, seed, &G); G.coins = 10; G.numBuys = 1; G.supplyCount[minion] = 0; funcStatus = buyCard(minion, &G); asserttrue((funcStatus == -1), " 0 minion left"); // -1 more minions left initializeGame(numPlayers, k, seed, &G); G.coins = 10; G.numBuys = 1; G.supplyCount[minion] = -1; funcStatus = buyCard(minion, &G); asserttrue((funcStatus == -1), "-1 minion left"); // no more province left initializeGame(numPlayers, k, seed, &G); G.coins = 10; G.numBuys = 1; G.supplyCount[province] = 0; funcStatus = buyCard(province, &G); asserttrue((funcStatus == -1), " 0 province left"); // -1 more province left initializeGame(numPlayers, k, seed, &G); G.coins = 10; G.numBuys = 1; G.supplyCount[province] = -1; funcStatus = buyCard(province, &G); asserttrue((funcStatus == -1), "-1 province left"); // no more silver left initializeGame(numPlayers, k, seed, &G); G.coins = 10; G.numBuys = 1; G.supplyCount[silver] = 0; funcStatus = buyCard(silver, &G); asserttrue((funcStatus == -1), " 0 silver left"); // -1 more silver left initializeGame(numPlayers, k, seed, &G); G.coins = 10; G.numBuys = 1; G.supplyCount[silver] = -1; funcStatus = buyCard(silver, &G); asserttrue((funcStatus == -1), "-1 silver left"); // ----------- TEST 4: cost too high -------------- printf("\n\nTEST 4: insufficient coins\n"); initializeGame(numPlayers, k, seed, &G); G.coins = 1; G.numBuys = 1; // buy estate: cost is 2, we have 1 funcStatus = buyCard(estate, &G); asserttrue((funcStatus == -1), "insufficient funds (1 coin buy estate)"); // negative coins G.coins = -1; G.numBuys = 1; // buy curse: cost is 0, we have -1 funcStatus = buyCard(curse, &G); asserttrue((funcStatus == -1), "insufficient funds (-1 coin buy curse)"); // ----------- TEST 5: successful buy: card in discard? -------------- printf("\n\nTEST 5: bought card in discard after buy\n"); initializeGame(numPlayers, k, seed, &G); G.coins = 10; G.numBuys = 1; thisPlayer = whoseTurn(&G); //discard should be empty to start asserttrue((G.discardCount[thisPlayer] == 0), "discard pile empty before buy"); funcStatus = buyCard(province, &G); asserttrue((funcStatus == 0), "buy province "); asserttrue((G.discardCount[thisPlayer] == 1), "discard pile 1 after buy"); asserttrue((G.discard[thisPlayer][0] == province), "discard pile top is province"); // ----------- TEST 6: successful buy: decremented supply count? -------------- printf("\n\nTEST 6: supply count decremented\n"); initializeGame(numPlayers, k, seed, &G); G.coins = 10; G.numBuys = 1; thisPlayer = whoseTurn(&G); // copy game state to testG to compare supply count afterward memcpy(&testG, &G, sizeof(struct gameState)); // do the buy, iterate to check each supply but province is same funcStatus = buyCard(province, &G); asserttrue((funcStatus == 0), "buy province"); for (i = 0; i < treasure_map+1; i++){ if (i == province){ asserttrue((supplyCount(province, &G) == (supplyCount(province, &testG)-1)), "province decremented"); } else { asserttrue((supplyCount(i, &G) == (supplyCount(i, &testG))), "not decremented"); } } // ----------- TEST 7: successful buy: hands of players same? -------------- printf("\n\nTEST 7: hands unchanged\n"); asserttrue((memcmp(&(G.hand),&(testG.hand), sizeof(G.hand)) == 0), "all hands same after buy"); asserttrue((memcmp(&(G.handCount),&(testG.handCount), sizeof(G.handCount)) == 0), "all hand counts same after buy"); // ----------- TEST 8: successful buy: decks of players same? -------------- printf("\n\nTEST 8: decks unchanged\n"); asserttrue((memcmp(&(G.deck),&(testG.deck), sizeof(G.deck)) == 0), "all decks same after buy"); asserttrue((memcmp(&(G.deckCount),&(testG.deckCount), sizeof(G.deckCount)) == 0), "all deck counts same after buy"); // ----------- TEST 9: successful buy: coins subtracted appropriately? -------------- printf("\n\nTEST 9: coins subtracted\n"); initializeGame(numPlayers, k, seed, &G); G.coins = 10; G.numBuys = 2; memcpy(&testG, &G, sizeof(struct gameState)); funcStatus = buyCard(province, &G); asserttrue((funcStatus == 0), "buy province"); asserttrue((G.coins+getCost(province) == testG.coins), "coins for province subtracted"); // ----------- TEST 10: successful buy: buys subtracted appropriately? -------------- printf("\n\nTEST 10: buys subtracted\n"); initializeGame(numPlayers, k, seed, &G); G.coins = 10; G.numBuys = 2; memcpy(&testG, &G, sizeof(struct gameState)); funcStatus = buyCard(province, &G); asserttrue((funcStatus == 0), "buy province"); asserttrue((G.numBuys+1 == testG.numBuys), "buys for province subtracted"); memcpy(&testG, &G, sizeof(struct gameState)); funcStatus = buyCard(province, &G); asserttrue((funcStatus == -1), "not buy province"); asserttrue((G.numBuys == testG.numBuys), "buys for province not subtracted"); memcpy(&testG, &G, sizeof(struct gameState)); funcStatus = buyCard(estate, &G); asserttrue((funcStatus == 0), "buy estate"); asserttrue((G.numBuys+1 == testG.numBuys), "buys for estate subtracted"); asserttrue((G.numBuys == 0), "0 buys remaining"); printf("\n\n\n"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "../inc/maze2.h" #include "../inc/set.h" #include "../inc/floodfill.h" #include "../inc/motion.h" #include "../inc/sensor.h" #include "../inc/exploration.h" #include "../inc/tests.h" U8 BitCount(U8 n) { U8 count = 0; while (n != 0) { count++; n &= (n - 1); } return count; } #ifndef __MM_COMP_AVR__ FILE* getFStream(const char *filename) { FILE* f = fopen(filename, "r"); printf("Reading file %s\n", filename); if (!f || ferror(f)) { perror("Error opening file"); return NULL; } return f; } void TestSet() { set_t setS; U16 i = 0; fprintf(stdout, "Testing Set\n"); setClearSet(&setS); for (; i < 255; i+=2) setSetBit(&setS, (U8)i); while (!setIsEmpty(&setS)) { printf("%d\n", setGetFirstAndClear(&setS)); } } void TestFF() { bitmap_t maze2; // create our maze bitmap_t maze; // import existing maze fprintf(stdout, "Testing FloodFill\n"); clearMap(&maze2); setWall(&maze2, 0, 0, EAST, 1); setWall(&maze2, 7, 8, EAST, 1); setWall(&maze2, 8, 8, EAST, 1); setWall(&maze2, 8, 8, NORTH, 1); setWall(&maze2, 8, 7, NORTH, 1); setWall(&maze2, 8, 7, WEST, 1); setWall(&maze2, 7, 7, WEST, 1); exportMap(stdout, &maze2); clearMap(&maze); importMap(fopen("../../../../mazes/1stworld.maze", "r"), &maze); exportMap(stdout, &maze); { set_t dest; // set the destination cells set_t visits; floodfill_t values; // get the ff values setClearSet(&visits); setClearSet(&dest); setSetBit(&dest, 119); setSetBit(&dest, 120); setSetBit(&dest, 135); setSetBit(&dest, 136); floodFill(&maze, &values, &dest); exportFF(stdout, &maze, &values, &visits, 0); } } C8 SkipWhitespaces(FILE *fp) { C8 c; fread(&c, sizeof(C8), 1, fp); while(IS_SPACE(c)) fread(&c, sizeof(C8), 1, fp); return c; } BOOL ReadMaze(bitmap_t* bitmap) { C8 buf[200]; FILE *fp; printf("Input maze file name: "); scanf("%s", buf); if(!strncmp(buf, "quit", 200)) { return FALSE; } fp = getFStream(buf); if(fp == NULL) { return FALSE; } importMap(fp, bitmap); return TRUE; } void TestExploration(const char* file) { U8 x, y; bitmap_t map; // existing map bitmap_t exmap; // exploration map clearMap(&map); clearMap(&exmap); // clear exploration map importMap(fopen(file, "r"), &map); setWall(&exmap, 0, 0, EAST, 1); // set starting wall exportMap(stdout, &exmap); { x = y = 0; // set start position set_t dest; // for destination cells floodfill_t values; // get the ff values set_t visits; // store visited cells U8 stopVar; // for scanf memset(&visits, 0, sizeof(set_t)); // clear visited cells visits.data[0] = 1; // starting cell is visited while (1) { setClearSet(&dest); // clear destination set setSetBit(&dest, ffGetPos(7,7)); // set destination cells setSetBit(&dest, ffGetPos(8,7)); setSetBit(&dest, ffGetPos(7,8)); setSetBit(&dest, ffGetPos(8,8)); floodFill(&exmap, &values, &dest); exportFF(stdout, &exmap, &values, &visits, 0); while (values.data[ffGetPos(y, x)] != 0) { U8 n,e,s,w; n = e = s = w = 255; scanf("%c", &stopVar); // pause for user // set all the walls if (getWall(&map, y, x, EAST)) setWall(&exmap, y, x, EAST, 1); else if (x+1 < 16) e = values.data[ffGetPos(y, x+1)]; if (getWall(&map, y, x, NORTH)) setWall(&exmap, y, x, NORTH, 1); else if (y+1 < 16) n = values.data[ffGetPos(y+1, x)]; if (getWall(&map, y, x, WEST)) setWall(&exmap, y, x, WEST, 1); else if (x != 0) w = values.data[ffGetPos(y, x-1)]; if (getWall(&map, y, x, SOUTH)) setWall(&exmap, y, x, SOUTH, 1); else if (y != 0) s = values.data[ffGetPos(y-1, x)]; // recalculate floodfill floodFill(&exmap, &values, &dest); exportFF(stdout, &exmap, &values, &visits, ffGetPos(y, x)); // draw floodfill map // find shortest path findMinPath(&n, &e, &s, &w, x, y, &visits); // move to lower value cell if (n) y++; else if (e) x++; else if (s) y--; else if (w) x--; // set cell as visited visits.data[ffGetPos(y, x)/8] |= (1 << (ffGetPos(y, x) % 8)); if (values.data[ffGetPos(y, x)] == 0) { // explore back to starting point scanf("%c", &stopVar); setClearSet(&dest); // clear destination set setSetBit(&dest, ffGetPos(0,0)); // set destination cell floodFill(&exmap, &values, &dest); exportFF(stdout, &exmap, &values, &visits, ffGetPos(y, x)); } } } } } #endif void TestSensors() { }
C
//priority q using array,ok #include<stdio.h> #include<conio.h> struct pqueue { int data; int priority; }; struct pqueue a[50]; int front=-1,rear=-1,max=50; void qinsert(int,int); int qdelete(); void create(); void additem(); void display(); void main() { int c,i; do { clrscr(); printf("\t\tM E N U"); printf("\n\t1.Create Queue"); printf("\n\t2.Add Item"); printf("\n\t3.Delete Item"); printf("\n\t4.Display Queue"); printf("\n\t5.Exit"); printf("\n\tEnter choice:-"); scanf("%d",&c); switch(c) { case 1: create(); break; case 2: if(front==-1 || rear==-1) break; else additem(); break; case 3: if(front==-1 || rear==-1) break; else qdelete(); break; case 4: if(front==-1 || rear==-1) break; else display(); break; case 5: printf("Exiting Program"); for(i=0;i<10;i++) { delay(600); printf("."); } exit(0); default: printf("\n\n\aWrong input\a"); break; } }while(1); } void qinsert(int item,int pro) { if(front==-1) front=rear=0; else if(rear==max-1) { printf("\nQueue is Full"); return; } else rear++; a[rear].data=item; a[rear].priority=pro; } int qdelete() { int c,pos,min; if(front==-1) { printf("\nEMPTY"); return; } else if(front==rear) { printf("\nDeleted element is :- %d",a[rear].data); rear=front=-1; } else { min=a[front].priority; pos=front; c=front+1; while(c<rear) { if(min>a[c].priority) { min=a[c].priority; pos=c; } c++; } printf("\nDeleted element is :- %d",a[pos].data); for(c=pos;c<rear;c++) { a[c].data=a[c+1].data; a[c].priority=a[c+1].priority; } rear=rear-1; } getch(); return; } void create() { int item,pos; printf("Enter Element :- "); scanf("%d",&item); printf("Enter Priority of Element (-999 to stop) :- "); scanf("%d",&pos); qinsert(item,pos); } void additem() { int x,pos; printf("\nAdd Item to List"); printf("\nEnter Element to Add :- "); scanf("%d",&x); printf("Enter Priority of Element (-999 to stop) :- "); scanf("%d",&pos); qinsert(x,pos); } void display() { int y=front; while(y<=rear) { printf("%d\t",a[y].data); y++; } printf("\n"); y=front; while(y<=rear) { printf("%d\t",a[y].priority); y++; } getch(); }
C
#include<stdio.h> #include<conio.h> #include<string.h> void main() { char name1[15]="Hello "; char name2[15]="World !"; clrscr(); printf("name1 =%s \t name2=%s",name1,name2); strcat(name1,name2); printf("\n After using the String cat Function"); printf("\n String at Name1 is %s ",name1); getch(); }
C
/* 5-12.c #include <stdio.h> int main(int argc, char* argv[ ]) { int i=0; printf("ڿ : %d \n", argc); for(i=0; i<argc; i++) { printf("argv[%d] : %s \n", i, argv[i]); } return 0; } */
C
#include "ft_printf.h" #include "ft_printfn.h" void ft_putchar_fd(char var, int fd) { write(fd, &var, fd); } static void ft_wrap_fd(t_mask *mask, int fd) { int cnt; cnt = 0; if (mask->prec) mask->wrapper.padding_sym = ' '; while (cnt < mask->wrapper.sym_amnt) { write(fd, &(mask->wrapper.padding_sym), 1); cnt++; } } static void ft_lclprint(t_mask *mask, char var, int fd) { if (mask->left_align) { ft_putchar_fd(var, fd); ft_wrap_fd(mask, fd); } else { ft_wrap_fd(mask, fd); ft_putchar_fd(var, fd); } } int ft_print_percent(t_mask *mask, va_list *arg, int fd) { char var; (void) arg; var = '%'; mask->wrapper.sym_amnt = mask->width - 1; ft_lclprint(mask, var, fd); if (mask->width > 0) return (mask->symbols_printed += mask->width); else return (mask->symbols_printed += 1); } int ft_print_char(t_mask *mask, va_list *arg, int fd) { char var; var = (char)va_arg(*arg, int); mask->wrapper.sym_amnt = mask->width - 1; ft_lclprint(mask, var, fd); if (mask->width > 0) mask->symbols_printed += mask->width; else mask->symbols_printed += 1; return (1); }
C
/************************************************************** * Subject: Numerical Methods & Programming * Purpose: Numerical Integration * Technique: Weddle's Rule * N.B.: Assumed given a function f(x), change the * definition of f(x) to match required function * or introduce an array if to compute using * tabular values **************************************************************/ #include <stdio.h> #include <math.h> float f(float x); int main(void) { float a,b,h,x,sum,ans; int coef[7],i,j; int n; /*** assign the coefficients ***/ coef[1]=5,coef[2]=1; coef[3]=6,coef[4]=1; coef[5]=5,coef[6]=2; /*** accept the necessary data ***/ printf("\nEnter the Starting Point: "); scanf("%f",&a); printf("\nEnter the End Point: "); scanf("%f",&b); printf("\nEnter the number of intervals: "); scanf("%d",&n); /*** check for the necessary condition ***/ if(n<6){ printf("\nAt least 7 consecutive values are reqd.\n"); exit(1); } /*** compute the step ***/ h=(b-a)/n; /*** integration process ***/ sum=0.0; i=1,j=1; while(i<n){ x=a+h*i; sum+=coef[j]*f(x); i++; j++; if(j>6) j=1; } sum+=f(a)+f(b); ans=sum*3*h/10; /*** display the result ***/ printf("\nThe Integral Value= %f\n\n",ans); return 0; } /***** function defined as f(x) *****/ float f(float x) { float y; y=1/(1+x); return y; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strsplit.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: arbocqui <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/11/26 21:06:21 by arbocqui #+# #+# */ /* Updated: 2020/02/26 18:26:18 by arbocqui ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include <stdlib.h> static char **ft_malloc_words(char const *str, char **table, char c) { int i; int nb_words; nb_words = 0; i = 0; while (str[i] == c) i++; while (str[i]) { i++; if (str[i] == c || str[i] == '\0') { nb_words++; while (str[i] == c) i++; } } if (!(table = (char**)malloc(sizeof(char*) * (nb_words + 1)))) return (0); table[nb_words] = 0; return (table); } static char **ft_malloc_words_letter(char const *str, char **table, char c) { int i; int x; int nb_wrd_let; nb_wrd_let = 1; i = 0; x = 0; while (str[i] == c) i++; while (str[i]) { i++; if (str[i] == c || str[i] == '\0') { if (!(table[x] = (char*)malloc(sizeof(char) * (nb_wrd_let + 1)))) return (0); x++; nb_wrd_let = 0; while (str[i] == c) i++; } nb_wrd_let++; } return (table); } static char **ft_concat_string(char const *str, char **table, char c) { int i; int x; int y; y = 0; x = 0; i = 0; while (str[i] == c) i++; while (str[i]) { table[x][y] = str[i]; y++; i++; if (str[i] == c || str[i] == '\0') { table[x][y] = '\0'; x++; y = 0; while (str[i] == c) i++; } } return (table); } char **ft_strsplit(char const *s, char c) { char **table; table = NULL; if (s && c) { if (!(table = ft_malloc_words(s, table, c))) return (NULL); if (!(table = ft_malloc_words_letter(s, table, c))) return (NULL); if (!(table = ft_concat_string(s, table, c))) return (NULL); } return (table); }
C
#include <stdio.h> #include <math.h> //lista 5 exercicio 9 int main() { float a, b, c, d, x1, x2; printf("\nInsira os coeficientes da equacao de 2 grau.: \n"); scanf("%f%f%f", &a, &b, &c); if(a!=0){ d = pow(b,2.0)-4.0*a*c; if(d==0.0){ printf("\nUma raiz\n"); x1=-b/(2.0*a); printf("\nRaiz: %f\n",x1); } if(d<0.0){ printf("\nNao existe raiz real\n"); } else if(d>0.0){ printf("\nDuas raizes reais\n"); x1 = (-b+ sqrtf(d))/(2.0*a); x2 = (-b- sqrtf(d))/(2.0*a); printf("\nraozes: %f, %f\n", x1, x2); } } else{ printf("\nOs valores nao formam uma equacao do 2 grau\n"); } return 0; }
C
#include <math.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include "em_general.h" int main(int argc, char **argv) { // number of arguments main takes if (argc != 2) { perror("Error: Invalid arguments\n"); exit(EXIT_FAILURE); } FILE *file; file = fopen(argv[1], "rb"); if (file == NULL) { perror("Error: File is null\n"); exit(EXIT_FAILURE); } // byte addressable memory State state = {{0}, {0}}; fread(state.memory, BYTE_SIZE, MEMORY_SIZE, file); fclose(file); pipeline(&state); return EXIT_SUCCESS; }
C
/* viet chuong trinh nhao day so thuc x1, x2,..,xn (0<n<100) Tim phan tu am lon nhat */ #include <stdio.h> #include <conio.h> #include <stdlib.h> main() { int i, n, dem = 0; float *a, max = -3.4e38; do { printf("Nhap so phan tu cua mang n = "); scanf("%d", &n); }while(n<=0 || n>=100); a = (float *)calloc(n, sizeof(float)); for(i=0; i<n; i++) { printf("a[%d] = ", i+1); scanf("%f", a+i); } printf("Day so vua nhap la\n"); for(i=0; i<n; i++) printf("%0.3f\t", *(a+i)); //-------------------------- for(i=0; i<n; i++) { if(*(a+i) < 0 && *(a+i) > max) { max = *(a+i); dem ++; } } printf("\n"); if(dem == 0) printf("Khong co phan tu am nao lon nhat"); else printf("Phan tu am lon nhat = %0.3f", max); free(a); return 0; }
C
struct words { int len; char word[20]; }; int main() { int n,i,size,count=0;; struct words *a; scanf("%d",&n); a=(struct words *)malloc(sizeof(struct words)*n); for (i=0;i<n;i++) { size=0; scanf("%s",&(a+i)->word); for (size=0;(a+i)->word[size]!='\0';size++); (a+i)->len=size; } count=0; for (i=0;i<n;i++) { if (count+(a+i)->len+1>80) { printf("\n"); count=0; i--; } else { if (count==0) { printf("%s",(a+i)->word); count=count+(a+i)->len; } else { printf(" %s",(a+i)->word); count=count+(a+i)->len+1; } } } }
C
#include "path.h" inherit FORESTROOM; void setup() { set_light(80); add_property("no_undead",1); set_short("Realm of the Elf: High Forest"); set_long("\n Realm of the Elf: High Forest.\n\n" " This looks like a peaceful well guarded part of the forest. " "There are lots of strange beautiful plants around here. " "The elves must really take care of this part of the " "forest, and keep it free of goblins and other pests. " "The air is filled with smells of grass and flowers. " "You hear birds singing their praise to nature. " "The trees are getting larger to the southeast. " "The track continues north and south from here. " "A small path turns off to the west away from the track." "\n\n"); add_item("plants", "These plants are various in size and shape. Although " "most are only a couple of inches high, others have grown taller than you!\n"); add_smell("air", "These air smells just like the air of spring would smell. " " You smell sents of red flowers, and green grass.\n"); add_item("path", "This path leads to the track to the west...Maybe you should" "follow it.\n"); add_exit("east", ROOM+"fo11", "road"); add_exit("north", ROOM+"fo6", "road"); add_exit("south", ROOM+"fo15", "road"); add_exit("west", ROOM+"center", "road"); add_item("forest", "The forest seems to be inhabited by lots of wildlife. " "Everywhere you look, you see small animals moving.\n"); set_zone("track"); }
C
#include<stdio.h> #include<stdlib.h> struct grafos{ int nVertices, ehPonderado, *grau; int **arestas, **pesos; }; typedef struct grafos Grafos; typedef struct{ int **mat; Grafos *gr; }Estados; struct pilha{ int n; struct pilha *prox; }; typedef struct pilha Pilha; Grafos* criaGrafo(int vertice, int ehPonderado); void insereAresta(Grafos **gr, int origem, int destino, int peso, int ehDigrafo); Estados *inicializaEst(); int tamaEst(int *estado); int temColisao(int *estado); int temSaida(int *estado); int** troca(int **mat); int *tira(int *estado); void printEstado(int *estado); int *tiraC(int *estado); int *proximoEstado(int *estAtual); int igual(int *est,int *est2); int procuraEst(int **estados,int *estado); void adj(Estados *est); void push(int v, Pilha **p); int MontaCam(Grafos *gr,int atual,Pilha **caminho,int *cont); void exibePilha(Pilha *P,Estados *est); void LigarEstados(Estados *est,int numeroEstados); int main(){ Estados *est=inicializaEst(); Pilha *p=NULL; int *test=(int*)calloc(4,sizeof(int)); printf("digite a configuração das formigas separadas por espaço: "); for(int i=0;i<4;i++){ scanf("%i",&test[i]); } // test=proximoEstado(test); // printEstado(test); // printf("%d\n",procuraEst(est->mat,test)); LigarEstados(est,30); // adj(est); int cont=0; MontaCam(est->gr,procuraEst(est->mat,test),&p,&cont); printf("As formigas vão passar por %d rodada(s) até saírem\nSendo elas:\n",cont); exibePilha(p,est); } int** troca(int **mat){ int i; for(i=0;i<16;i++){ for(int j=0;j<4;j++){ if(mat[i][j]==0) mat[i][j]=-1; } } for(i=i;i<24;i++){ for(int j=0;j<3;j++){ if(mat[i][j]==0) mat[i][j]=-1; } } for(i=i;i<28;i++){ for(int j=0;j<2;j++){ if(mat[i][j]==0) mat[i][j]=-1; } } return mat; } Grafos* criaGrafo(int vertice, int ehPonderado){ Grafos *gr; int i; gr = (Grafos*)malloc(sizeof(Grafos)); if(gr != NULL){ gr->nVertices = vertice; gr->ehPonderado = (ehPonderado != 0)? 1:0; gr->grau = (int*) calloc(sizeof(int), vertice); gr->arestas = (int**) malloc(vertice * sizeof(int*)); for(i=0; i<vertice; i++){ gr->arestas[i] = (int*) calloc(vertice, sizeof(int)); } if(gr->ehPonderado){ gr->pesos = (int**) malloc(vertice * sizeof(int*)); for(i=0; i<vertice; i++){ gr->pesos[i] = (int*) calloc(vertice, sizeof(int)); } } } return gr; } void insereAresta(Grafos **gr, int origem, int destino, int peso, int ehDigrafo){ if(*gr != NULL){ if(origem >= 0 && origem <= (*gr)->nVertices){ if(destino > 0 && destino <= (*gr)->nVertices){ (*gr)->arestas[origem][(*gr)->grau[origem]] = destino; } if((*gr)->ehPonderado){ (*gr)->pesos[origem][(*gr)->grau[origem]] = peso; } (*gr)->grau[origem]++; if(!ehDigrafo){ insereAresta(gr, destino, origem, peso, 1); } } } } Estados *inicializaEst(){ Estados *est=(Estados*)malloc(sizeof(Estados)); est->gr=criaGrafo(31,0); est->mat=(int**)malloc(sizeof(int*)*31); int cont=0; int aa=1,bb=1,cc=1,dd=1; for (int i = 0; i < 16; ++i) { est->mat[cont]=(int*)calloc(4,sizeof(int)); if (!(i % 8)) aa = !aa; if (!(i % 4)) bb = !bb; if (!(i % 2)) cc = !cc; dd = !dd; est->mat[cont][0]=aa; est->mat[cont][1]=bb; est->mat[cont][2]=cc; est->mat[cont][3]=dd; cont++; } bb=1,cc=1,dd=1; for (int i = 0; i < 8; ++i) { est->mat[cont]=(int*)calloc(3,sizeof(int)); if (!(i % 4)) bb = !bb; if (!(i % 2)) cc = !cc; dd = !dd; est->mat[cont][0]=bb; est->mat[cont][1]=cc; est->mat[cont][2]=dd; cont++; } cc=1,dd=1; for (int i = 0; i < 4; ++i) { est->mat[cont]=(int*)calloc(2,sizeof(int)); if (!(i % 2)) cc = !cc; dd = !dd; est->mat[cont][0]=cc; est->mat[cont][1]=dd; cont++; } est->mat[cont]=(int*)calloc(1,sizeof(int)); est->mat[cont][0]=-1; cont++; est->mat[cont]=(int*)calloc(1,sizeof(int)); est->mat[cont][0]=1; cont++; est->mat[cont]=(int*)calloc(1,sizeof(int)); est->mat[cont][0]=0; est->mat=troca(est->mat); return est; } int tamaEst(int *estado){ int tam=0; for(tam=0;estado[tam]!=0;tam++); return tam; } int temColisao(int *estado){ int retorno=0; int tam=tamaEst(estado); for(int i=0;i<tam-1 && retorno==0;i++) if(estado[i]==1 && estado[i+1]==-1) retorno=1; return retorno; } int temSaida(int *estado){ int retorno=0; int tam=tamaEst(estado); if(estado[0]==-1 || estado[tam-1]==1) retorno=1; return retorno; } int *tira(int *estado){ int ini=0,end=tamaEst(estado),novoTam=end; if(estado[ini]==-1){ novoTam-=1; ini=1; } if(estado[end-1]==1){ novoTam-=1; end-=1; } int *NovoEstado=(int*)malloc(sizeof(int)*novoTam); int cont=0; for(int i=ini;i<end;i++,cont++){ NovoEstado[cont]=estado[i]; } return NovoEstado; } void printEstado(int *estado){ int tam = tamaEst(estado); printf("("); for(int i = 0; i < tam-1; i++) printf("%d,", estado[i]); printf("%d)\n", estado[tam-1]); } int *tiraC(int *estado){ int tam=tamaEst(estado); int *prox=(int*)malloc(sizeof(int*)*tam); for(int i=0;i<tam;i++){ prox[i]=estado[i]; } for(int i=0;i<tam-1;i++){ if(prox[i]==1 && prox[i+1]==-1){ prox[i]*=-1; prox[i+1]*=-1; i++; } } return prox; } int *proximoEstado(int *estAtual){ int *prox; if(temColisao(estAtual)){ if(temSaida(estAtual)){ prox=tira(estAtual); estAtual=prox; } prox=tiraC(estAtual); }else if(temSaida(estAtual)){ prox=tira(estAtual); } return prox; } int igual(int *est,int *est2){ int t=tamaEst(est2); int retorno=1; for(int i=0;i<t && retorno==1;i++){ if(est[i]!=est2[i]) retorno=0; } return retorno; } int procuraEst(int **estados,int *estado){ int retorno = -1; for(int i=0;i<31 && retorno==-1;i++){ int t=tamaEst(estados[i]); if(t==tamaEst(estado)){ if(igual(estados[i],estado)){ retorno=i; } } } } void LigarEstados(Estados *est,int numeroEstados){ for(int i=0;i<numeroEstados;i++){ int *prox=proximoEstado(est->mat[i]); int dest=procuraEst(est->mat,prox); insereAresta(&est->gr,i,dest,0,1); } } void adj(Estados *est){ for(int i=0;i<30;i++){ printf("Estado %d ",i);printEstado(est->mat[i]); for(int j=0;j<est->gr->grau[i];j++){ printf("Vai para o Estado %d ",est->gr->arestas[i][j]);printEstado(est->mat[est->gr->arestas[i][j]]); } } } void push(int v, Pilha **p){ Pilha *cel=(Pilha*)malloc(sizeof(Pilha)); cel->n=v; cel->prox=*p; *p=cel; } int MontaCam(Grafos *gr,int atual,Pilha **caminho,int *cont){ int i; push(atual,caminho); for(i=0; i<gr->grau[atual]; i++){ *cont+=1; MontaCam(gr, gr->arestas[atual][i], caminho, cont); } } void exibePilha(Pilha *P,Estados *est){ Pilha *aux = P; if(aux!=NULL){ exibePilha(P->prox,est); printf("%d:",aux->n);printEstado(est->mat[aux->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 */ int FD_CLOEXEC ; int /*<<< orphan*/ F_DUPFD ; int /*<<< orphan*/ F_DUPFD_CLOEXEC ; int /*<<< orphan*/ F_GETFD ; int /*<<< orphan*/ PROTECT_ERRNO ; int /*<<< orphan*/ assert (int) ; int /*<<< orphan*/ close (int) ; int fcntl (int,int /*<<< orphan*/ ,int) ; int fd_move_above_stdio(int fd) { int flags, copy; PROTECT_ERRNO; /* Moves the specified file descriptor if possible out of the range [0…2], i.e. the range of * stdin/stdout/stderr. If it can't be moved outside of this range the original file descriptor is * returned. This call is supposed to be used for long-lasting file descriptors we allocate in our code that * might get loaded into foreign code, and where we want ensure our fds are unlikely used accidentally as * stdin/stdout/stderr of unrelated code. * * Note that this doesn't fix any real bugs, it just makes it less likely that our code will be affected by * buggy code from others that mindlessly invokes 'fprintf(stderr, …' or similar in places where stderr has * been closed before. * * This function is written in a "best-effort" and "least-impact" style. This means whenever we encounter an * error we simply return the original file descriptor, and we do not touch errno. */ if (fd < 0 || fd > 2) return fd; flags = fcntl(fd, F_GETFD, 0); if (flags < 0) return fd; if (flags & FD_CLOEXEC) copy = fcntl(fd, F_DUPFD_CLOEXEC, 3); else copy = fcntl(fd, F_DUPFD, 3); if (copy < 0) return fd; assert(copy > 2); (void) close(fd); return copy; }
C
#include <stdlib.h> #include <stdint.h> #include <unistd.h> #include <string.h> #include "esp_log.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "rom/uart.h" #include "include/flipdot.h" #include "include/snake.h" #include "include/fill.h" #include "include/text.h" static const char* TAG = "Snake"; // The dotboard for the snake mode static dotboard_t dots; // Define our snake static snake_t snake; // Define a treat static coordinate_t treat; /** * Listen for keystrokes on the UART and update the snake direction. */ static void update_direction_user(snake_t* snake) { uint8_t read_char; STATUS s = uart_rx_one_char(&read_char); if (s == OK) { // Change the direction as appropriate switch (read_char) { case 'w': if (snake->direction != DIRECTION_DOWN) { snake->direction = DIRECTION_UP; ESP_LOGI(TAG, "Changed direction to UP"); } break; case 'a': if (snake->direction != DIRECTION_RIGHT) { snake->direction = DIRECTION_LEFT; ESP_LOGI(TAG, "Changed direction to LEFT"); } break; case 's': if (snake->direction != DIRECTION_UP) { snake->direction = DIRECTION_DOWN; ESP_LOGI(TAG, "Changed direction to DOWN"); } break; case 'd': if (snake->direction != DIRECTION_LEFT) { snake->direction = DIRECTION_RIGHT; ESP_LOGI(TAG, "Changed direction to RIGHT"); } break; } } } /** * Use a fill algorithm to decide the next best direction change. */ static void update_direction_ai(snake_t* snake) { uint8_t read_char; STATUS s = uart_rx_one_char(&read_char); if (s == OK) { // Change the direction as appropriate switch (read_char) { case 'w': if (snake->direction != DIRECTION_DOWN) { snake->direction = DIRECTION_UP; ESP_LOGI(TAG, "Changed direction to UP"); } break; case 'a': if (snake->direction != DIRECTION_RIGHT) { snake->direction = DIRECTION_LEFT; ESP_LOGI(TAG, "Changed direction to LEFT"); } break; case 's': if (snake->direction != DIRECTION_UP) { snake->direction = DIRECTION_DOWN; ESP_LOGI(TAG, "Changed direction to DOWN"); } break; case 'd': if (snake->direction != DIRECTION_LEFT) { snake->direction = DIRECTION_RIGHT; ESP_LOGI(TAG, "Changed direction to RIGHT"); } break; } } } /** * Advance the snake position by one tick. */ static void update_position(snake_t* snake) { // Capture the previous head position coordinate_t old_head; old_head.x = snake->head.x; old_head.y = snake->head.y; // Update with the new head position based on direction snake->head.y -= (snake->direction >> 0) & 1; snake->head.y += (snake->direction >> 1) & 1; snake->head.x -= (snake->direction >> 2) & 1; snake->head.x += (snake->direction >> 3) & 1; // Shift the tail along for (int tail_i = snake->tail_length; tail_i > 0; tail_i --) { snake->tail[tail_i] = snake->tail[tail_i - 1]; } // Change the tail segment right next to the head to be the "old" head snake->tail[0] = old_head; } /** * Randomly place a treat on the board. */ static void place_treat() { treat.x = 1 + (rand() % (DOT_COLUMNS - 2)); treat.y = 1 + (rand() % (DOT_ROWS - 2)); ESP_LOGI(TAG, "Treat placed @ %d x %d", treat.x, treat.y); } /** * Detect collisions with walls, snake tail segments and treats. */ static void detect_collisions(snake_t* snake) { // We extend by one if we eat a treat if (snake->head.x == treat.x && snake->head.y == treat.y) { snake->tail_length ++; place_treat(); ESP_LOGI(TAG, "Ate a treat, tail length extended to %d", snake->tail_length); } #ifdef TOROIDAL // Implement a toroidal map if (snake->head.x == 0 && snake->direction == DIRECTION_LEFT) { snake->head.x = DOT_COLUMNS - 1; } if (snake->head.x == DOT_COLUMNS && snake->direction == DIRECTION_RIGHT) { snake->head.x = 0; } if (snake->head.y == 0 && snake->direction == DIRECTION_UP) { snake->head.y = DOT_ROWS - 1; } if (snake->head.y == DOT_ROWS && snake->direction == DIRECTION_DOWN) { snake->head.y = 0; } #else // We're dead if we touch the walls if ( (snake->head.x == 0 && snake->direction == DIRECTION_LEFT) || (snake->head.x == DOT_COLUMNS - 1 && snake->direction == DIRECTION_RIGHT) || (snake->head.y == 0 && snake->direction == DIRECTION_UP) || (snake->head.y == DOT_ROWS - 1 && snake->direction == DIRECTION_DOWN) ) { ESP_LOGI(TAG, "Wall collision detected - snake killed"); snake->is_dead = true; return; } #endif // We're dead if we touch our tail for (int tail_i = 0; tail_i < snake->tail_length; tail_i ++) { if (snake->head.x == snake->tail[tail_i].x && snake->head.y == snake->tail[tail_i].y) { ESP_LOGI(TAG, "Tail collision detected - snake killed"); snake->is_dead = true; return; } } } /** * Initialise the snake game. */ void snake_init() { snake.is_dead = false; snake.head.x = DOT_COLUMNS / 2; snake.head.y = DOT_ROWS / 2; snake.direction = DIRECTION_RIGHT; snake.tail_length = 3; place_treat(); } /** * We've died, show the score and check for any key to resume */ void death_screen() { // Draw "GAME OVER" text fill_off(&dots); render_text_4x5(&dots, 0, 1, "GAME"); render_text_4x5(&dots, 1, 7, "OVER"); write_dotboard(&dots, false); uint8_t read_char; STATUS s = uart_rx_one_char(&read_char); if (s == OK) { ESP_LOGI(TAG, "Starting new game!"); snake_init(); } } void snake_update() { // Detect any collisions that occurred in the last frame if (!snake.is_dead) { // Alter direction update_direction_user(&snake); detect_collisions(&snake); } if (snake.is_dead) { death_screen(); return; } // Clear the frame-buffer fill_off(&dots); // Advance the snake position update_position(&snake); // Draw the snake head to the dotboard dots[snake.head.x][snake.head.y] = 1; // Draw the snake tail to the dotboard for (int tail_i = 0; tail_i < snake.tail_length; tail_i ++) { dots[snake.tail[tail_i].x][snake.tail[tail_i].y] = 1; } // Draw the treat dots[treat.x][treat.y] = 1; // Draw the dotboard write_dotboard(&dots, false); // Inter-frame delay inversely proportional to the tail length vTaskDelay((100 - snake.tail_length * 2) / portTICK_RATE_MS); }
C
/* external dependencies * ────────────────────────────────────────────────────────────────────────── */ #include "tasty_regex_run.h" #include "tasty_regex_utils.h" /* helper macros * ────────────────────────────────────────────────────────────────────────── */ #ifdef __cplusplus # define NULL_POINTER nullptr /* use c++ null pointer constant */ #else # define NULL_POINTER NULL /* use traditional c null pointer macro */ #endif /* ifdef __cplusplus */ /* typedefs, struct declarations * ────────────────────────────────────────────────────────────────────────── */ /* used for tracking accumulating matches during run */ struct TastyAccumulator { const union TastyState *state; /* currently matching regex */ struct TastyAccumulator *next; /* next parallel matching state */ const unsigned char *match_from; /* beginning of string match */ }; /* helper functions * ────────────────────────────────────────────────────────────────────────── */ static inline void push_next_acc(struct TastyAccumulator *restrict *const restrict acc_list, struct TastyAccumulator *restrict *const restrict acc_alloc, const struct TastyRegex *const restrict regex, const unsigned char *const restrict string) { const union TastyState *restrict state; const union TastyState *restrict next_state; state = regex->initial; while (1) { next_state = state->step[*string]; /* if no match on string */ if (next_state == NULL_POINTER) { /* check skip route */ next_state = state->skip; /* if DNE or skipped all the way to end w/o explicit * match, do not add new acc to acc_list */ if ( (next_state == NULL_POINTER) || (next_state == regex->matching)) return; state = next_state; /* explicit match */ } else { /* pop a fresh accumulator node */ struct TastyAccumulator *const restrict acc = *acc_alloc; ++(*acc_alloc); /* populate it and push into acc_list */ acc->state = next_state; acc->next = *acc_list; acc->match_from = string; *acc_list = acc; return; } } } static inline void push_match(struct TastyMatch *restrict *const restrict match_alloc, const unsigned char *const restrict from, const unsigned char *const restrict until) { /* pop a fresh match node */ struct TastyMatch *const restrict match = *match_alloc; ++(*match_alloc); /* populate */ match->from = (const char *) from; match->until = (const char *) until; } static inline void acc_list_process(struct TastyAccumulator *restrict *restrict acc_ptr, struct TastyMatch *restrict *const restrict match_alloc, const union TastyState *const restrict matching, const unsigned char *const restrict string) { struct TastyAccumulator *restrict acc; const union TastyState *restrict state; const union TastyState *restrict next_state; acc = *acc_ptr; while (acc != NULL_POINTER) { state = acc->state; /* if last step was a match */ if (state == matching) { /* push new match */ push_match(match_alloc, acc->match_from, string); /* remove acc from list */ acc = acc->next; *acc_ptr = acc; /* step to next state */ } else { while (1) { next_state = state->step[*string]; /* if no match on string */ if (next_state == NULL_POINTER) { /* check skip route */ next_state = state->skip; /* if DNE */ if (next_state == NULL_POINTER) { /* remove acc from list */ acc = acc->next; *acc_ptr = acc; break; /* if skipped all the way to end w/o * explicit match, close match */ } else if (next_state == matching) { /* push new match */ push_match(match_alloc, acc->match_from, string); /* remove acc from list */ acc = acc->next; *acc_ptr = acc; break; } /* continue looking for explicit * match */ state = next_state; /* explicit match found, update acc */ } else { /* update accumulator state and * traversal vars */ acc->state = next_state; acc_ptr = &acc->next; acc = acc->next; break; } } } } } static inline void acc_list_final_scan(struct TastyAccumulator *restrict acc, struct TastyMatch *restrict *const restrict match_alloc, const union TastyState *const restrict matching, const unsigned char *const restrict string) { const union TastyState *restrict state; while (acc != NULL_POINTER) { state = acc->state; /* if last step was a match */ if (state == matching) { /* push new match */ push_match(match_alloc, acc->match_from, string); /* check if skip route can match */ } else { while (1) { state = state->skip; /* if dead end, bail */ if (state == NULL_POINTER) break; /* if skipping yields match, record */ if (state == matching) { /* push new match */ push_match(match_alloc, acc->match_from, string); break; } } } acc = acc->next; } } /* API * ────────────────────────────────────────────────────────────────────────── */ int tasty_regex_run(const struct TastyRegex *const restrict regex, struct TastyMatchInterval *const restrict matches, const char *restrict string) { struct TastyMatch *restrict match_alloc; struct TastyAccumulator *restrict acc_alloc; struct TastyAccumulator *restrict acc_list; /* want to ensure at least 1 non-'\0' char before start of walk */ if (*string == '\0') { matches->from = NULL_POINTER; matches->until = NULL_POINTER; return 0; } const size_t length_string = nonempty_string_length(string); /* at most N matches */ match_alloc = malloc(sizeof(struct TastyMatch) * length_string); if (UNLIKELY(match_alloc == NULL_POINTER)) return TASTY_ERROR_OUT_OF_MEMORY; /* at most N running accumulators */ struct TastyAccumulator *const restrict accumulators = malloc(sizeof(struct TastyAccumulator) * length_string); if (UNLIKELY(accumulators == NULL_POINTER)) { free(match_alloc); return TASTY_ERROR_OUT_OF_MEMORY; } acc_alloc = accumulators; /* point acc_alloc to valid memory */ acc_list = NULL_POINTER; /* initialize acc_list to empty */ matches->from = match_alloc; /* set start of match interval */ /* walk string */ while (1) { /* push next acc if explicit start of match found */ push_next_acc(&acc_list, &acc_alloc, regex, (const unsigned char *) string); ++string; if (*string == '\0') break; /* traverse acc_list: update states, prune dead-end accs, and * append matches */ acc_list_process(&acc_list, &match_alloc, regex->matching, (const unsigned char *) string); } /* append matches found in acc_list */ acc_list_final_scan(acc_list, &match_alloc, regex->matching, (const unsigned char *) string); /* close match interval */ matches->until = match_alloc; /* free temporary storage */ free(accumulators); /* return success */ return 0; } /* free allocations */ extern inline void tasty_match_interval_free(struct TastyMatchInterval *const restrict matches);
C
#include <stdio.h> #define TRUE 1 #define FALSE 0 /* contig: collapse contiguous spaces into a single space */ int main() { int c, inspace = FALSE; while ((c = getchar()) != EOF) { if (c == ' ') { if (!inspace) { inspace = TRUE; } else { continue; } } else if (c != ' ' && inspace) inspace = FALSE; putchar(c); } return 0; }
C
#include <stdio.h> #include <string.h> /* * Program Name: convertLowerCase.c * Author(s): Rehan Nagoor Mohideen * Student ID: 1100592 * Purpose: Convert all alphabetic characters to lower case. Returns the number of characters converted from upper case to low */ int convertLowerCase ( char *line ){ int i; int noofChar = 0; for (i = 0; i <= strlen(line); i++) { if (line[i]>64 && line[i]<91){ /* Find where the uppercase character are to replace */ line[i]=line[i]+32; noofChar++; } } return noofChar; }
C
#include <msp430.h> #include <libTimer.h> #include "lcdutils.h" #include "lcddraw.h" #include "p2switches.h" #define LED_GREEN BIT6 // P1.6 short redrawScreen = 1; u_int fontFgColor = COLOR_GREEN; u_char helloCol = 10; u_char nextHelloCol =10; signed char helloVelocity = 1; // move one pixel to right void wdt_c_handler() { static int secCount = 0; // timer static int dsecCount = 0;// dsecCount++; secCount ++; if (secCount == 250) { // reset counter secCount = 0; fontFgColor = (fontFgColor == COLOR_GREEN) ? COLOR_BLACK : COLOR_GREEN; // change font Color redrawScreen = 1; // set redrawScreen to meanin screen was redrawn } if (dsecCount ==25){ // if 25 reset counter dsecCount =0; nextHelloCol += helloVelocity; // Add Variables if ( nextHelloCol > 30 || nextHelloCol <=10) {// reverse direction helloVelocity = -helloVelocity; nextHelloCol += helloVelocity; } redrawScreen =1; // screen redrawn. (interrupt) } } /*void change_to_triangle(){ static char state; if(redrawScreecn){ redrawScreen = 0; switch(state){ case 0: } }*/ void advance(){ u_int switches = p2sw_read(); char str[5]; // Corresponding switches 1,2,3,4 str[0] = (switches & (1<<0)) ? 0 :1; str[1] = (switches & (1<<1)) ? 0 :1; str[2] = (switches & (1<<2)) ? 0 :1; str[3] = (switches & (1<<3)) ? 0 :1; // If button 1 is pressed then shape_1() is drawn to the screen // After it is released the Screen is cleared. if (str[0]){ shape1(); } else if(str[1]){ shape2(); } else if(str[2]){ shape3(); } else if(str[3]){ shape4(); } else { clearScreen(COLOR_BLACK); } } void main(){ P1DIR |= LED_GREEN; /**< Green led on when CPU on */ P1OUT |= LED_GREEN; configureClocks(); p2sw_init(15); lcd_init(); enableWDTInterrupts(); /**< enable periodic interrupt */ or_sr(0x8); /**< GIE (enable interrupts) */ clearScreen(COLOR_BLACK); while (1) { assy_change(); advance(); if (redrawScreen) { /*If screen is set to 1 */ redrawScreen = 0; /* set it to 0 or off */ drawString11x16(helloCol,20, "WELCOME", COLOR_BLACK, COLOR_BLACK); drawString11x16(nextHelloCol,20, "WELCOME", fontFgColor, COLOR_BLACK); helloCol = nextHelloCol; } P1OUT &= ~LED_GREEN; /* green off*/ or_sr(0x10); /**< CPU OFF **/ P1OUT |= LED_GREEN; /* green on*/ } }
C
#include<stdio.h> #include<stdlib.h> #include<string> struct Node{ int size; int top; char *arr; }; int isFull(struct Node *ptr){ int top = ptr->top; int size = ptr->size; if(top==size-1){ // printf("The stack is now full"); return 1; }else{ return 0; } } int isEmpty(struct Node *ptr){ int top = ptr->top; int size = ptr->size; if(top==-1){ return 1; }else{ return 0; } } void push(struct Node *ptr,char data){ ptr->top++; ptr->arr[ptr->top] = data; } char pop(struct Node *ptr){ char value = ptr->arr[ptr->top]; ptr->top--; return value; } int stacktop(struct Node *arr){ return arr->arr[arr->top]; } char *infixtopostfix(char *infix){ struct Node *sp; sp->size = 100; sp->top = -1; sp->arr = (char *)malloc(sp->size*sizeof(struct Node)); char *postfix= (char *)malloc((strlen(infix)+1)*sizeof(char)); int i=0; // for infix int j=0; // for postfix while(infix[i]!='\0'){ if(!isOperator(infix[i])){ postfix[j] = infix[i]; j++; i++; }else{ if(precednce(infix[i])>precedence(stacktop(sp))){ push(sp,infix[i]); i++; }else{ postfix[j] = pop(sp); j++; } } } } int main(){ char *infix = "a-b+t/6"; return 0; }
C
#define _WINSOCK_DEPRECATED_NO_WARNINGS //ͷļݲִСд #include<stdio.h> #include<WinSock2.h> #pragma comment(lib, "ws2_32.lib") int main(void) { // //typedef unsigned short WORD; WORD wdVersion = MAKEWORD(2, 2); //ֽڷ汾ţֽڷŸ汾 WSADATA wdMsgStr; //ִгɹ᷵0 //ЩʵǺ궨 int nRes = WSAStartup(wdVersion, &wdMsgStr); //봦 if (nRes != 0) { switch (nRes) { case WSASYSNOTREADY: printf("ϵͳ\n"); break; case WSAVERNOTSUPPORTED: printf("\n"); break; case WSAEINPROGRESS: printf("\n"); break; case WSAEFAULT: printf("˿ڱռ\n"); break; } } //汾У //HIBYTE LOBYTE ȡֵĸֽں͵ֽ if (2 != HIBYTE(wdMsgStr.wVersion) || 2 != LOBYTE(wdMsgStr.wVersion)) { //򿪵İ汾 //߹ر WSACleanup(); return -1; } //һsocket,SOCKETʾһ //һip(ipv4) ڶ ʽsocket TCPЭ SOCKET socketServer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //׽ʹҪ -- closesocket(SOCKET s) //ʧܷINVALID_SOCKET if (INVALID_SOCKET == socketServer) { //ȡʧܵĴ, Ҫ֮ãҪӦϽ int a = WSAGetLastError(); //׽ִʧܣֱӹر WSACleanup(); return -1; } //Ӻ //int bind(SOCKET s, const sockaddr *addr, int namelen) //һ ׽ // sockaddrָ // sockaddrij struct sockaddr_in si; si.sin_family = AF_INET; //htonsתunsigned int si.sin_port = htons(50000); si.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); if (bind(socketServer, (const struct sockaddr*)&si, sizeof(si)) == SOCKET_ERROR) { //ִг //ȡ int a = WSAGetLastError(); //ر׽ closesocket(socketServer); //ر WSACleanup(); return -1; } //ʼ if (SOCKET_ERROR == listen(socketServer, SOMAXCONN)) { //ʧ //ȡ int a = WSAGetLastError(); //ر׽ֺ closesocket(socketServer); WSACleanup(); return -1; } //ͨ //ͻ˵׽ struct sockaddr_in clientMsg; int len = sizeof(clientMsg); //òͻ˵׽֣ڶΪNULL SOCKET socketclient = accept(socketServer, (struct sockaddr*)&clientMsg, &len); if (INVALID_SOCKET == socketclient) { //ȡʧܵĴ, Ҫ֮ãҪӦϽ int a = WSAGetLastError(); printf("ͻӳɹ\n"); closesocket(socketServer); closesocket(socketclient); //׽ִʧܣֱӹر WSACleanup(); return -1; } //ڴһֱȵͻӣ(ͬ) printf("ͻӳɹ\n"); char buf[1500] = { 0 }; //recvҲ̣ȿͻ˴ //4 -- //Ĭд0 ȡ֮ɾĿռ int res = recv(socketclient, buf, 1499, 0); if (0 == res) { printf("ͻж..."); } else if (SOCKET_ERROR == res) { //Ϣͳ int error_code = WSAGetLastError(); switch (error_code) { default: break; } } printf("%d %s\n", res, buf); //ȹرsocketڹر⣬SOCKTE closesocket(socketServer); closesocket(socketclient); WSACleanup(); system("pause"); return 0; }
C
/* include if_nametoindex */ #include "unpifi.h" #include "unproute.h" unsigned int if_nametoindex(const char *name) { unsigned int idx, namelen; char *buf, *next, *lim; size_t len; struct if_msghdr *ifm; struct sockaddr *sa, *rti_info[RTAX_MAX]; struct sockaddr_dl *sdl; if ( (buf = net_rt_iflist(0, 0, &len)) == NULL) return(0); namelen = strlen(name); lim = buf + len; for (next = buf; next < lim; next += ifm->ifm_msglen) { ifm = (struct if_msghdr *) next; if (ifm->ifm_type == RTM_IFINFO) { sa = (struct sockaddr *) (ifm + 1); get_rtaddrs(ifm->ifm_addrs, sa, rti_info); if ( (sa = rti_info[RTAX_IFP]) != NULL) { if (sa->sa_family == AF_LINK) { sdl = (struct sockaddr_dl *) sa; if (sdl->sdl_nlen == namelen && strncmp(&sdl->sdl_data[0], name, sdl->sdl_nlen) == 0) { idx = sdl->sdl_index; /* save before free() */ free(buf); return(idx); } } } } } free(buf); return(0); /* no match for name */ } /* end if_nametoindex */ unsigned int If_nametoindex(const char *name) { int idx; if ( (idx = if_nametoindex(name)) == 0) err_quit("if_nametoindex error for %s", name); return(idx); }
C
#include <stdio.h> struct fun { int x; } a = { 32 }; void pfun2(struct fun **z) { } void pfun(struct fun *z) { pfun2(&z); printf("%d\n", z->x); } int main(int argc, char **argv) { pfun(&a); return 0; }
C
#include<stdio.h> int strend(char *s,char *t,int l,int m); void main() { int l,m; char a[20],b[10]; printf("enter the string a :"); gets(a); printf("enter the string b :"); gets(b); l=strlen(a); m=strlen(b); strend(a,b,l,m); } int strend(char *s,char *t,int l,int m) { int i,j; for(i=l-1,j=m-1;i>=l-m;i--,j--) { if(*(s+i)!=*(t+j)) {return 0; break;} else return 1; } }
C
#include <stdio.h> #include <stdlib.h> typedef struct binary_search_tree { int item; int h; struct binary_search_tree *right; struct binary_search_tree *left; }binary_search_tree; binary_search_tree* create_empty_bst() { return NULL; } binary_search_tree* create_binary_search_tree(int item, binary_search_tree *left, binary_search_tree *right) { binary_search_tree *new_binary_search_tree = (binary_search_tree*) malloc(sizeof(binary_search_tree)); new_binary_search_tree->item = item; new_binary_search_tree->h = 0; new_binary_search_tree->left = left; new_binary_search_tree->right = right; return new_binary_search_tree; } binary_search_tree* search(binary_search_tree *bt, int item) { if (bt == NULL || bt->item == item) { return bt; } else if (bt->item > item) { return search(bt->left, item); } else { return search(bt->right, item); } } binary_search_tree* search_n_recursivo(binary_search_tree *bt, int item) { binary_search_tree *aux = bt; while(aux != NULL) { if (aux->item == item) { break; } else if (aux->item > item) { aux = aux->left; } else { aux = aux->right; } } return aux; } int max(int a, int b) { return (a > b) ? a : b; } int h(binary_search_tree *bt) { if (bt == NULL) { return -1; } else { return 1 + max(h(bt->left), h(bt->right)); } } int balance_factor(binary_search_tree *bt) { if (bt == NULL) { return 0; } else if ((bt->left != NULL) && (bt->right != NULL)) { return (bt->left->h - bt->right->h); } else if ((bt->left != NULL) && (bt->right == NULL)) { return (1 + bt->left->h); } else { return(-(bt->right->h) - 1); } } binary_search_tree* rotate_left(binary_search_tree *bt) { binary_search_tree *subtree_root = NULL; if (bt != NULL && bt->right != NULL) { subtree_root = bt->right; bt->right = subtree_root->left; subtree_root->left = bt; } subtree_root->h = h(subtree_root); bt->h = h(bt); return subtree_root; } binary_search_tree* rotate_right(binary_search_tree *bt) { binary_search_tree *subtree_root = NULL; if (bt != NULL && bt->left != NULL) { subtree_root = bt->left; bt->left = subtree_root->right; subtree_root->right = bt; } subtree_root->h = h(subtree_root); bt->h = h(bt); return subtree_root; } binary_search_tree* add(binary_search_tree *bt, int item) { if(bt == NULL) { return create_binary_search_tree(item, NULL, NULL); } else if(bt->item > item) { bt->left = add(bt->left, item); } else { bt->right = add(bt->right, item); } bt->h = h(bt); binary_search_tree *child = NULL; if (balance_factor(bt) == 2 || balance_factor(bt) == -2) { if (balance_factor(bt) == 2) { child = bt->left; if (balance_factor(child) == -1) { bt->left = rotate_left(child); } bt = rotate_right(bt); } else if(balance_factor(bt) == -2) { child = bt->right; if (balance_factor(child) == 1) { bt->right = rotate_right(child); } bt = rotate_left(bt); } } return bt; } //retorna o node de menor valor de uma BST binary_search_tree* menor_node(binary_search_tree *bt) { binary_search_tree *current = bt; while(current->left != NULL) { current = current->left; } return current; } //REMOVE AINDA NÃO IMPLEMENTADO!!!! /* binary_search_tree* remove_node(binary_search_tree *bt, int item) { if(bt == NULL)return bt; if(bt->item > item) { bt->left = remove_node(bt->left, item); } else if(bt->item < item) { bt->right = remove_node(bt->right, item); } else { //node com 1 ou 0 filhos if(bt->right == NULL) { binary_search_tree *aux = bt->left; free(bt); return aux; } else if(bt->left == NULL) { binary_search_tree *aux = bt->right; free(bt); return aux; } //node com 2 filhos //nos dá o menor node da sub tree a direita do bt binary_search_tree *aux = menor_node(bt->right); bt->item = aux -> item; bt->right = remove_node(bt->right, aux->item); } return bt; } */ //REMOVE DANDO SEGMENTAL FAULT!!!! /* binary_search_tree* remove_node(binary_search_tree *bt, int item) { if(bt == NULL)return bt; if(bt->item > item) { bt->left = remove_node(bt->left, item); } else if(bt->item < item) { bt->right = remove_node(bt->right, item); } else { //node com 1 ou 0 filhos if(bt->right == NULL) { binary_search_tree *aux = bt->left; free(bt); return aux; } else if(bt->left == NULL) { binary_search_tree *aux = bt->right; free(bt); return aux; } //node com 2 filhos //nos dá o menor node da sub tree a direita do bt binary_search_tree *aux = menor_node(bt->right); bt->item = aux -> item; bt->right = remove_node(bt->right, aux->item); } if (bt == NULL) { return NULL; } bt->h = h(bt); binary_search_tree *child = NULL; if (balance_factor(bt) == 2 || balance_factor(bt) == -2) { if (balance_factor(bt) == 2) { child = bt->left; if (balance_factor(child) == -1) { bt->left = rotate_left(child); } bt = rotate_right(bt); } else if(balance_factor(bt) == -2) { child = bt->right; if (balance_factor(child) == 1) { bt->right = rotate_right(child); } bt = rotate_left(bt); } } return bt; } */ void print_pre_order(binary_search_tree *bt) { if (bt != NULL) { printf("%d ", bt->item); print_pre_order(bt->left); print_pre_order(bt->right); } } int main() { binary_search_tree *bt = create_empty_bst(); bt = add(bt, 51); bt = add(bt, 26); bt = add(bt, 11); bt = add(bt, 6); bt = add(bt, 8); bt = add(bt, 4); bt = add(bt, 31); bt = remove_node(bt, 26); print_pre_order(bt); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> //strlen #include<sys/socket.h> #include<arpa/inet.h> //inet_addr #include<pthread.h> #define Buffer_size 200 volatile sig_atomic_t flag = 0; int sockfd = 0; void str_overwrite_stdout() { printf("%s", "> "); fflush(stdout); } void str_trim_lf (char* arr, int length) { int i; for (i = 0; i < length; i++) { // trim \n if (arr[i] == '\n') { arr[i] = '\0'; break; } } } void catch_ctrl_c_and_exit(int sig) { flag = 1; } void SendMsg() { char message[Buffer_size] = {}; char buffer[Buffer_size] = {}; while(1) { str_overwrite_stdout(); fgets(message, Buffer_size, stdin); str_trim_lf(message, Buffer_size); if (strcmp(message, "exit") == 0) break; else { sprintf(buffer, "%s\n", message); send(sockfd, buffer, strlen(buffer), 0); } bzero(message, Buffer_size); bzero(buffer, Buffer_size); } catch_ctrl_c_and_exit(2); } void RecvMsg() { char message[Buffer_size] = {0}; while (1) { int receive = (int)recv(sockfd, message, Buffer_size, 0); if (receive > 0) { printf("%s", message); str_overwrite_stdout(); } else if (receive == 0) break; memset(message, 0, sizeof(message)); } } int main(int argc , char *argv[]) { int socket_desc; struct sockaddr_in server; // char *message , server_reply[500],server_reply2[500]; //Create socket socket_desc = socket(AF_INET , SOCK_STREAM , 0); if (socket_desc == -1) { printf("Не могу создать розетку"); } sockfd=socket_desc; //server.sin_addr.s_addr = inet_addr("127.0.0.0"); server.sin_family = AF_INET; server.sin_port = htons( 8000 ); //Connect to remote server if (connect(socket_desc , (struct sockaddr *)&server , sizeof(server)) < 0) { puts("Ошибка подключения"); return 1; } puts("Подключено\n"); pthread_t recv_msg_thread; pthread_create(&recv_msg_thread, NULL, (void *) RecvMsg, NULL); pthread_t send_msg_thread; pthread_create(&send_msg_thread, NULL, (void *) SendMsg, NULL); // for(int i=0; i<2;i++) // { // if( recv(socket_desc, server_reply , 2000 , 0) < 0) // { // puts("Не принял"); // } // puts("Пришел ответ\n"); // puts(server_reply); // } // char buff[200]; // /// char *ukaz=NULL; // scanf("%99[^\n]",buff); // message=buff; // if( send(socket_desc , message , strlen(message) , 0) < 0) // { // puts("Не отправил"); // return 1; // } // if( recv(socket_desc, server_reply2 , 2000 , 0) < 0) // { // puts("Не принял"); // } // puts("Пришел ответ\n"); // puts(server_reply2); while (1) if(flag) { printf("\nBye\n"); break; } shutdown(socket_desc, SHUT_RD);//(socket_desc); return 0; }
C
#include <stdlib.h> #include "team.h" struct Team create_team(int population, char* names[], int* favorites) { // struct Person member; struct Team output; int i; output.population = population; output.people = malloc(sizeof(struct Person) * population); for (i = 0; i < population; i++) { output.people[i].favorite = malloc(sizeof(struct Person)); (output.people[i].favorite -> name) = *(names + favorites[i]); (output.people[i].name) = *(names + i); } return (output); } void free_team(struct Team* team) { for (int k = 0; k < team->population; k++) { free(team->people[k].favorite); } free(team->people); } /* struct Person* pick_leader(struct Team* team) { } */
C
//Michael Morris //CS 3060-001 Spring 2015 //Assignment #3 /* Promise of Originality I promise that this source code file has, in it's entirety, been writthen by myself and by no other person or persons. If at any time an exact copy of this source code is found to be used by another person this term, I understand that both myself and the student that submitted the copy will receive a zero on this assignment. */ #include<stdio.h> #include<pthread.h> #include<stdlib.h> int primes[100]; int ind = 0; void* factor(void* input) { int d = atoi(input); int i; ind = 0; for(i = 2; i <= d; i++){ if(d % i == 0){ d = d / i; primes[ind] = i; i = 1; //set i to 1 so that when it increments, it goes to 2 and tests 2 again for the d ind++; } } pthread_exit(0); }//end factor int main(int argc, char *argv[]) { int i; int j; pthread_t t; if(argc < 2){ //make sure there are arguments to factor printf("Usage: ./assn3 <number to factor>...\n"); return -1; } for(i = 1; i < argc; i++){ //make sure the arguments are positive integers if(atoi(argv[i]) <= 0){ printf("Arguments must be positive integers\n"); return -1; } } for(i = 1; i < argc; i++){ pthread_create(&t, NULL, factor, (void*)argv[i]); pthread_join(t, NULL); printf("%d: %d", atoi(argv[i]), primes[0]); for(j = 1; j < ind; j++) printf(", %d", primes[j]); printf("\n"); } return 0; }//end main