language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/******************************************************************************/ /*Files to Include */ /******************************************************************************/ #include <stdint.h> /* For uint8_t definition */ #include <stdbool.h> #include <pic18f4685.h> /* For true/false definition */ #include "spi.h" void spi_init() { TRISCbits.RC4 = 1; // SDI as input TRISCbits.RC5 = 0; // SDO as output TRISCbits.RC3 = 0; // SCK/SCL as output (cleared) TRISCbits.TRISC6 = 0; //CSG TRISCbits.TRISC7 = 0; //CSXM SSPCON1bits.SSPEN = 0; // Clear bit to reset, SPI pins SSPCON1bits.CKP = 1; // Set polarity to idle at 1 SSPSTATbits.CKE = 0; // Set transmit on rising edge SSPSTATbits.SMP = 0; // Set Sample bit to 0 SSPCON1bits.SSPM0 = 0; // Set SSPM[3:0] as stated in manual SSPCON1bits.SSPM1 = 0; // In order to divide by 4 (Fosc/4) SSPCON1bits.SSPM2 = 0; SSPCON1bits.SSPM3 = 0; SSPCON1bits.WCOL = 0; // Clear the write buffer SSPCON1bits.SSPEN = 1; // Set bit to re enable SPI } unsigned int spi_data_ready() { return SSPSTATbits.BF; } char spi_read() { while(!SSPSTATbits.BF); return SSPBUF; } void spi_write(char message) { //while(SSPCON1bits.WCOL); SSPBUF = message; } unsigned long spi_read_long() { unsigned long total = 0; for(int i = 0; i < 4; i++) { total += spi_read() << (i * 8); } return total; } char oneReadCycle(char num) { delay_milli(30); spi_write(num); // Send command to slave char measure; delay_milli(30); if(spi_data_ready()) { measure = spi_read(); } return measure; } void delay_milli(unsigned int time) { for (int i = 0; i < time; i++) __delay_ms(1); }
C
/** @file * Interfejs obsługujący logikę gry * * @author Jan Olszewski * @copyright Uniwersytet Warszawski * @date 16.05.2020 */ #ifndef LOGIC_H #define LOGIC_H #include "gamma.h" /** @brief typ mówiący o trybie, w którym ma być rozgrywana rozgrywka */ enum mode{Batch, Interactive}; /** @brief struktura przechowująca stan gry * i informacje o trybie, w którym będzie rozgrywana rozgrywka */ typedef struct{ gamma_t* game; ///< struktura przechowująca stan gry enum mode mod; ///< zmienna mówiąca o trybie przeprowadzaniej rozgrywki } game_and_mode; /** @brief parsuje kolejne linie inputu, jeżeli jest zgodna ze specyfikacją * tworzy gre i mówi w jakim trybie będzie przeprowadzana rozgrywka * param[in] gm - struktura przechowująca stan gry * i informacje o trybie, w którym będzie rozgrywana rozgrywka * param[in] line - numer przetwarzanej lini * * @return true jeżeli udało się wykonać akcję, false wpp */ bool set_game_and_mode(game_and_mode* gm, int* line); /** @brief przeprowadza rozgrywkę w trybie wsadowym * param[in] game - struktura przechowująca stan gry * param[in] line - numer przetwarzanej lini */ void play_batch(gamma_t* game, int* line); /** @brief przeprowadza rozgrywkę w trybie interaktywnym * param[in] game - struktura przechowująca stan gry */ void play_interactive(gamma_t* game); /** @brief wypisuje komunikat zabija proces * param[in] str - komunikat jaki ma zostać wypisany przed zabiciem procesu */ void fail(char* str); /** @brief wypisuje komunikat ERROR line, gdzie * line to numer lini, w której pojawił się błąd * param[in] line - numer przetwarzanej lini */ void errLine(int line); /** @brief wypisuje komunikat ERROR */ void err(); #endif
C
#include<stdio.h> main() { int a,b; printf("Enter two number\n"); scanf("%d%d",&a,&b); a^b?printf("Not equal"):printf("Equal"); }
C
#include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <assert.h> #define N 10 /* * A permutation is an ordered arrangement of objects. For example, 3124 is one * possible permutation of the digits 1, 2, 3 and 4. If all of the permutations * are listed numerically or alphabetically, we call it lexicographic order. The * lexicographic permutations of 0, 1 and 2 are: * * 012 021 102 120 201 210 * * What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, * 5, 6, 7, 8 and 9? */ static long long *seen = NULL; static int seenlen = 0; static int maxseenlen = 0; /* a is an array of integers with exactly 1 of every digit from 1 to N */ void add(char *a) { int i; long long n = 0; for (i = 0; i < N; i++) { n *= 10; n += a[i]; } // add to list of seen sets seenlen++; if (seenlen > maxseenlen) { maxseenlen += 100000; seen = realloc(seen, sizeof(long long)*maxseenlen); if(!seen) { perror("check"); exit(1); } } seen[seenlen-1] = n; } static int cmp(const void *a, const void *b) { long long a1, b1; a1 = *(long long*)a; b1 = *(long long*)b; if (a1 < b1) { return -1; } else if (a1 > b1) { return 1; } else { return 0; } } int main(void) { char array[N]; /* generate all permutations of array using non-recursive implementation of * Heap's method */ int i; char c[N]; for (i = 0; i < N; i++) { c[i] = 0; array[i] = i; } add(array); for (i = 1; i < N; ) { if (c[i] < i) { int j = i % 2 ? c[i] : 0; int temp = array[j]; array[j] = array[i]; array[i] = temp; c[i]++; i = 1; add(array); } else { c[i] = 0; i++; } } assert(seenlen > 1000000); qsort(seen, seenlen, sizeof(seen[0]), cmp); printf("%lld\n", seen[999999]); return 0; }
C
/* ************************************************************************** */ /* */ /* :::::::: */ /* filler.c :+: :+: */ /* +:+ */ /* By: wvan-ees <[email protected]> +#+ */ /* +#+ */ /* Created: 2019/07/16 15:14:52 by wvan-ees #+# #+# */ /* Updated: 2019/07/16 15:14:54 by wvan-ees ######## odam.nl */ /* */ /* ************************************************************************** */ #include "filler.h" /* *** Fills the 2d array created to store the piece with the piece given as input */ static int fill_piece(t_piece *piece, int fd) { int i; char *str; while (piece->ycnt < piece->y) { if (!(get_next_line(fd, &str))) exit(1); i = 0; while (str[i]) { piece->piece[piece->ycnt][i] = str[i]; i++; } piece->piece[piece->ycnt][i] = '\n'; piece->piece[piece->ycnt][i + 1] = '\0'; piece->ycnt++; free(str); } return (1); } /* *** Allocates the necessary memory for 2d array which will contain the piece to be placed */ static int make_piece(t_piece *piece) { int y; y = 0; piece->piece = (char**)malloc(sizeof(char*) * piece->y + 1); if (piece->piece == NULL) error(); piece->piece[piece->y] = NULL; while (y < piece->y) { piece->piece[y] = (char*)malloc(sizeof(char) * piece->x + 1); if (piece->piece[y] == NULL) error(); y++; } return (1); } /* *** Saves the x & y dimensions of the piece given as input with each new round. *** These dimensions are later used to size the piece. */ static void size_piece(t_piece *piece, int fd) { int i; char *str; i = 6; if (!(get_next_line(fd, &str))) exit(1); while (str[i] && str[i] >= '0' && str[i] <= '9') { piece->y *= 10; piece->y += str[i] - '0'; i++; } i++; while (str[i] && str[i] >= '0' && str[i] <= '9') { piece->x *= 10; piece->x += str[i] - '0'; i++; } free(str); make_piece(piece); } /* *** calculates the offset of each piece if one is present */ static void calc_off(t_piece *piece) { int y; int x; y = 0; piece->y_off = piece->y; piece->x_off = piece->x; while (piece->piece[y]) { x = 0; while (piece->piece[y][x]) { if (piece->piece[y][x] == '*') { if (x < piece->x_off) piece->x_off = x; if (y < piece->y_off) piece->y_off = y; } x++; } y++; } } /* *** Handles the actual playing of the game. Which continues while a piece can be placed. *** The grid is updated by fill_grid, the dimensions of the piece are obtained by size_piece *** and used to create a 2d array which can fit the piece. *** The x & y co-ordinates of the best possible position (the one closest to the nearest enmey piece) *** are given to the standard output. */ void filler(t_filler *stuff, t_piece *piece) { int run; run = 1; while (run) { if (fill_grid(stuff)) { size_piece(piece, stuff->t_fd); fill_piece(piece, stuff->t_fd); calc_off(piece); if (place(stuff, piece) < 0) { ft_printf("0 0\n"); run = 0; } initialize(piece, stuff); } } free_grid(stuff->grid); }
C
#include <stdio.h> #include <stdlib.h> struct nodo { TipoDato elemento; struct nodo* siguiente; }; typedef struct nodo Nodo; typedef struct { Nodo* Frente; Nodo* Final; }Cola; // * Los prototipos de las operaciones * / void CrearCola(Cola* Q); // * Tnicializa la cola como vacía */ void InsertarQ(Cola* Q,Tipo»dto elemento); TipoDato EliminarQ(Cola* Q); void BorrarCola(Cola* Q); // * acceso a la cola * / TipoDato FrenteQ(Co1a Q); /* métodos de verificación del estado de la cola */ int Qvacia(Co1a Q);
C
#include "stdio.h" static const char *colors[] = {" c black", ". c #001100", "X c #111100"}; int main() { unsigned char code; char color[32]; int rcode; for (int i = 0; i < 3; i++) { rcode = sscanf(colors[i], "%c c %s", &code, color); printf("%i, %c, %s\n", rcode, code, color); } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strjoin.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: iniska <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/07/16 07:11:20 by iniska #+# #+# */ /* Updated: 2023/07/17 12:26:50 by iniska ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> int ft_strlen(char *str) { char i; i = 0; while (*str++) { i++; } return (i); } char *ft_strcpy(char *dest, char *src) { int i; i = 0; while (src[i] != '\0') { dest[i] = src[i]; i++; } dest[i] = '\0'; return (dest); } int ft_final_lenght(char **strs, int size, int sep_l) { int fin_len; int i; fin_len = 0; i = 0; while (i < size) { fin_len += ft_strlen(strs[i]); fin_len += sep_l; i++; } fin_len -= sep_l; return (fin_len); } char *ft_strjoin(int size, char **strs, char *sep) { int full; int i; char *dest; char *source; if (size == 0) return ((char *)malloc(sizeof(char))); full = ft_final_lenght(strs, size, ft_strlen(sep)); dest = (char *)malloc((full + 1) * sizeof(char)); source = dest; if (!source) return (0); i = -1; while (i++ < size) { source = ft_strcpy(source, strs[i]); source += ft_strlen(strs[i]); if (i < size -1) { source = ft_strcpy(source, sep); source += ft_strlen(sep); } } *source = '\0'; return (dest); } #include <stdio.h> #include <string.h> int main(void) { char **strs; char *separator; char *result; int size = 3; strs = (char **)malloc(size * sizeof(char *)); strs[0] = (char *)malloc((strlen("I like") + 1) * sizeof(char)); strs[1] = (char *)malloc((strlen("banananas") + 1) * sizeof(char)); strs[2] = (char *)malloc((strlen("and lemons :)") + 1) * sizeof(char)); strcpy(strs[0], "I like"); strcpy(strs[1], "banananas"); strcpy(strs[2], "and lemons :)"); separator = " "; result = ft_strjoin(size, strs, separator); printf("%s$\n", result); free(result); free(strs[0]); free(strs[1]); free(strs[2]); free(strs); return (0); }
C
int getlettervalue(char letter) { if(letter == 'I') { return 1; } else if(letter == 'V') { return 5; } else if(letter == 'X') { return 10; } else if(letter == 'L') { return 50; } else if(letter == 'C') { return 100; } else if(letter == 'D') { return 500; } else if(letter == 'M') { return 1000; } } int romanToInt(char* s) { int len = strlen(s); int ans = 0; ans += getlettervalue(s[0]); for(int i = 1; i < len; i++) { if(getlettervalue(s[i]) > getlettervalue(s[i-1])) { ans -= getlettervalue(s[i-1]); ans -= getlettervalue(s[i-1]); ans += getlettervalue(s[i]); } else { ans += getlettervalue(s[i]); } } return ans; }
C
/* fuxiti4.c -- ϰ4*/ #include <stdio.h> #include <stdlib.h> struct month{ char mname[30]; char suoxie[3]; int days; int No; }; void printall(struct month); int main(void) { struct month year[12]; struct month amonth; int i; for(i = 0; i < 12; i++) { amonth = year[i]; amonth.No = i + 1; switch(i) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: amonth.days = 31; break; case 2: amonth.days = 28; default: amonth.days = 30; } switch(i) { case 1: // sscanf(amonth.mname, "January"); amonth.mname = "January"; amonth.suoxie = "Jan."; break; case 2: amonth.mname = "February"; amonth.suoxie = "Feb."; break; case 3: amonth.mname = "March"; amonth.suoxie = "Mar."; break; case 4: amonth.mname = "April"; amonth.suoxie = "Apr."; break; case 5: amonth.mname = "May"; amonth.suoxie = "May."; break; case 6: amonth.mname = "June"; amonth.suoxie = "Jun."; break; case 7: amonth.mname = "July"; amonth.suoxie = "Jul."; break; case 8: amonth.mname = "August"; amonth.suoxie = "Aug."; break; case 9: amonth.mname = "September"; amonth.suoxie = "Sep."; break; case 10: amonth.mname = "October"; amonth.suoxie = "Oct."; break; case 11: amonth.mname = "November"; amonth.suoxie = "Nov"; break; case 12: amonth.mname = "December"; amonth.suoxie = "Dec"; break; } } printall(year); return 0; } void printall(struct month year) { int i; for(i=0; i < 12; i++) { printf("%s %s %d %d\n", year[i].mname, year[i].suoxie, year[i].days, year[i].No); } }
C
#include <cstdio> #include <cstring> #include <ctype.h> char a[50], len = 0; void d(char c) { int i; for(i = 0; i < len; i++) if(a[i] == c) break; if(i == len) return; for(; i < len; i++) a[i] = a[i + 1]; len--; } void insert(char c1, char c2) { int i, index; for(i = 0, index = -1; i < len; i++) if(a[i] == c1) index = i; if(index == -1) return; for(i = len; i > index; i--) a[i] = a[i - 1]; a[index] = c2; len++; } void replace(char c1, char c2) { int i; for(i = 0; i < len; i++) if(a[i] == c1) a[i]=c2; } int main() { char o, a1, a2; while((o = getchar()) != '.') a[len++] = o; a[len++] = '.'; while(isspace(o = getchar())); if(o == 'D') { while(isspace(a1 = getchar())); d(a1); } else if(o == 'I') { while(isspace(a1 = getchar())); while(isspace(a2 = getchar())); insert(a1, a2); } else { while(isspace(a1 = getchar())); while(isspace(a2 = getchar())); replace(a1, a2); } for(int i = 0; i < len; i++) printf("%c", a[i]); printf("\n"); return 0; }
C
#include <stdio.h> #define MAX_LEN 25 int main(int argc, char* argv[]) { char name[MAX_LEN]; printf("What is your name? "); scanf("%s", name); printf("Hello, %s, nice to meet you!\n", name); return 0; }
C
#include "test_utilities.h" #include <stdlib.h> #include <ctype.h> #include <inttypes.h> #include <string.h> #include "../memcache.h" #define ASSERT_TRUE(x) ASSERT_TEST(x); #define ASSERT_EQUAL(x,y) ASSERT_TEST((x) == (y)); #define ASSERT_EQUAL_STR(x,y) ASSERT_TEST(strcmp((x),(y)) == 0); #define ASSERT_SUCCESS(x) ASSERT_EQUAL((x), MEMCACHE_SUCCESS); #define ASSERT_NOT_NULL(x) ASSERT_TRUE(x) #define ASSERT_NULL(x) ASSERT_TRUE(!x) /** Functions to be used for checking blocks' status */ static bool checkBlock(void* ptr, int size, char mod, const char* const username, char* data) { char* block = ptr; block -= (sizeof(int) + 1 + 8 + 3); ASSERT_EQUAL(size, *(int*)block); block += sizeof(int); ASSERT_EQUAL(*block, '\0'); block += 1; ASSERT_EQUAL(*block, mod); block += 1; ASSERT_EQUAL_STR(username, block); block += strlen(username) + 1; ASSERT_EQUAL(*block, '\0'); block += 1; if (data != NULL) ASSERT_EQUAL_STR(data, block); return true; } bool memCacheExampleTest() { MemCache memcache; ASSERT_NOT_NULL(memcache = memCacheCreate()); ASSERT_SUCCESS(memCacheAddUser(memcache, "jbond007", 1000)); ASSERT_SUCCESS(memCacheAddUser(memcache, "j0walker", 500)); char *ptr1 = NULL; ASSERT_NOT_NULL(ptr1 = memCacheAllocate(memcache, "jbond007", 10)); char *ptr2 = NULL; ASSERT_NOT_NULL(ptr2 = memCacheAllocate(memcache, "j0walker", 50)); strcpy(ptr1, "A string."); strcpy(ptr2, "Some other string."); ASSERT_SUCCESS(memCacheSetBlockMod(memcache, "jbond007", ptr1, 'G')); ASSERT_TRUE(checkBlock(ptr1, 10, 'G', "jbond007", "A string.")); ASSERT_TRUE(checkBlock(ptr2, 50, 'U', "j0walker", "Some other string.")); ASSERT_SUCCESS(memCacheTrust(memcache, "jbond007", "j0walker")); ASSERT_EQUAL(memCacheFree(memcache, "jbond007", ptr2), MEMCACHE_PERMISSION_DENIED); ASSERT_SUCCESS(memCacheFree(memcache, "j0walker", ptr1)); ASSERT_NOT_NULL(memCacheGetFirstFreeBlock(memcache)); ASSERT_NOT_NULL(memCacheGetFirstAllocatedBlock(memcache)); memCacheDestroy(memcache); return true; } static bool memCacheCreateTest(void) { MemCache memcache = memCacheCreate(); ASSERT_NOT_NULL(memcache); memCacheDestroy(memcache); return true; } static bool memCacheDestroyTest(void) { // is NULL stable memCacheDestroy(NULL); // use all possible structures to detect leak MemCache memcache = memCacheCreate(); ASSERT_NOT_NULL(memcache); const int ALLOCATED_CACHE_SIZE = (1<<10); const int FREE_CACHE_SIZE = 256; const int ALL_POSSIBLE_ALLOCATED_BLOCKS_SUM = (1+ALLOCATED_CACHE_SIZE)*ALLOCATED_CACHE_SIZE/2; const int ALL_POSSIBLE_FREE_BLOCKS_SUM = (1+FREE_CACHE_SIZE)*FREE_CACHE_SIZE/2; // add users char * username1 = "LepsGena"; char * username2 = "Coldplay"; ASSERT_SUCCESS(memCacheAddUser(memcache, username1, ALL_POSSIBLE_ALLOCATED_BLOCKS_SUM)); ASSERT_SUCCESS(memCacheAddUser(memcache, username2, ALL_POSSIBLE_FREE_BLOCKS_SUM)); //allocate memory void *user1Memory[ALLOCATED_CACHE_SIZE]; void *user2Memory[FREE_CACHE_SIZE]; for (int size = 1; size <= ALLOCATED_CACHE_SIZE; ++size) { user1Memory[size-1] = memCacheAllocate(memcache, username1, size); ASSERT_NOT_NULL(user1Memory[size-1]); ASSERT_TRUE(checkBlock(user1Memory[size-1], size, 'U', username1, NULL)); } for (int size = 1; size <= FREE_CACHE_SIZE; ++size) { user2Memory[size-1] = memCacheAllocate(memcache, username2, size); ASSERT_NOT_NULL(user2Memory[size-1]); memCacheSetBlockMod(memcache, username2, user2Memory[size-1], 'G'); ASSERT_TRUE(checkBlock(user2Memory[size-1], size, 'G', username2, NULL)); } //user1 and user2 trust each other ASSERT_SUCCESS(memCacheTrust(memcache, username1, username2)); ASSERT_SUCCESS(memCacheTrust(memcache, username2, username1)); //user1 frees all memory user2 has, while latter is sleeping for (int size = 1; size <= FREE_CACHE_SIZE; ++size) { ASSERT_SUCCESS(memCacheFree(memcache, username1, user2Memory[size-1])); } //user2 doesn't trusts to user1 anymore ASSERT_SUCCESS(memCacheUntrust(memcache, username2, username1)); //start some iterations ASSERT_NOT_NULL(memCacheGetFirstFreeBlock(memcache)); ASSERT_NOT_NULL(memCacheGetFirstAllocatedBlock(memcache)); memCacheDestroy(memcache); return true; } static bool memCacheAddUserTest(void) { MemCache memcache = memCacheCreate(); ASSERT_NOT_NULL(memcache); char *user1 = "AxelRudi"; char *shortUser = "AxelRud"; char *longUser = "AxelRudiP"; char *emptyUser = ""; ASSERT_EQUAL(memCacheAddUser(NULL, user1, 23), MEMCACHE_NULL_ARGUMENT); ASSERT_EQUAL(memCacheAddUser(NULL, user1, -1), MEMCACHE_NULL_ARGUMENT); ASSERT_EQUAL(memCacheAddUser(memcache, NULL, 23), MEMCACHE_ILLEGAL_USERNAME); ASSERT_EQUAL(memCacheAddUser(memcache, user1, 0), MEMCACHE_INVALID_ARGUMENT); ASSERT_EQUAL(memCacheAddUser(memcache, user1, -1), MEMCACHE_INVALID_ARGUMENT); ASSERT_EQUAL(memCacheAddUser(memcache, shortUser, -1), MEMCACHE_INVALID_ARGUMENT); ASSERT_EQUAL(memCacheAddUser(memcache, shortUser, 23), MEMCACHE_ILLEGAL_USERNAME); ASSERT_EQUAL(memCacheAddUser(memcache, longUser, 23), MEMCACHE_ILLEGAL_USERNAME); ASSERT_EQUAL(memCacheAddUser(memcache, emptyUser, 23), MEMCACHE_ILLEGAL_USERNAME); for (int i = 0; i < 8; ++i) { for (int c = 0; c < 256; ++c) { if (!isalnum(c)) { char illegalName[9]; strcpy(illegalName, "legal123"); illegalName[i] = c; ASSERT_EQUAL(memCacheAddUser(memcache, illegalName, 23), MEMCACHE_ILLEGAL_USERNAME); } } } memCacheDestroy(memcache); return true; } static bool memCacheSetBlockModTest(void) { MemCache memcache = memCacheCreate(); ASSERT_NOT_NULL(memcache); //users char * user1 = "gammaray"; char * user2 = "scorpion"; char * user3 = "amaranth"; char * user4 = "nightwis"; // add users to system ASSERT_SUCCESS(memCacheAddUser(memcache, user1, 100)); ASSERT_SUCCESS(memCacheAddUser(memcache, user2, 100)); ASSERT_SUCCESS(memCacheAddUser(memcache, user3, 100)); // relations ASSERT_SUCCESS(memCacheTrust(memcache, user1, user2)); // allocations void *block1 = memCacheAllocate(memcache, user1, 10); ASSERT_NOT_NULL(block1); ASSERT_TRUE(checkBlock(block1, 10, 'U', user1, NULL)); void *block2 = memCacheAllocate(memcache, user2, 23); ASSERT_NOT_NULL(block2); ASSERT_TRUE(checkBlock(block2, 23, 'U', user2, NULL)); // releasing ASSERT_SUCCESS(memCacheFree(memcache, user2, block2)); ASSERT_EQUAL(memCacheSetBlockMod(NULL, NULL, NULL, 'B'), MEMCACHE_NULL_ARGUMENT); ASSERT_EQUAL(memCacheSetBlockMod(memcache, NULL, NULL, 'B'), MEMCACHE_USER_NOT_FOUND); ASSERT_EQUAL(memCacheSetBlockMod(memcache, user4, NULL, 'B'), MEMCACHE_USER_NOT_FOUND); ASSERT_EQUAL(memCacheSetBlockMod(memcache, user1, NULL, 'B'), MEMCACHE_BLOCK_NOT_ALLOCATED); ASSERT_EQUAL(memCacheSetBlockMod(memcache, user1, (char*)block1+1, 'B'), MEMCACHE_BLOCK_NOT_ALLOCATED); ASSERT_TRUE(checkBlock(block1, 10, 'U', user1, NULL)); ASSERT_EQUAL(memCacheSetBlockMod(memcache, user1, block2, 'B'), MEMCACHE_BLOCK_NOT_ALLOCATED); ASSERT_EQUAL(memCacheSetBlockMod(memcache, user2, block2, 'B'), MEMCACHE_BLOCK_NOT_ALLOCATED); ASSERT_EQUAL(memCacheSetBlockMod(memcache, user2, block1, 'B'), MEMCACHE_PERMISSION_DENIED); ASSERT_TRUE(checkBlock(block1, 10, 'U', user1, NULL)); ASSERT_EQUAL(memCacheSetBlockMod(memcache, user1, block1, 'B'), MEMCACHE_INVALID_ARGUMENT); ASSERT_TRUE(checkBlock(block1, 10, 'U', user1, NULL)); ASSERT_SUCCESS(memCacheSetBlockMod(memcache, user1, block1, 'U')); ASSERT_TRUE(checkBlock(block1, 10, 'U', user1, NULL)); ASSERT_SUCCESS(memCacheSetBlockMod(memcache, user1, block1, 'G')); ASSERT_TRUE(checkBlock(block1, 10, 'G', user1, NULL)); ASSERT_EQUAL(memCacheSetBlockMod(memcache, user2, block1, 'A'), MEMCACHE_PERMISSION_DENIED); ASSERT_TRUE(checkBlock(block1, 10, 'G', user1, NULL)); ASSERT_SUCCESS(memCacheSetBlockMod(memcache, user1, block1, 'A')); ASSERT_TRUE(checkBlock(block1, 10, 'A', user1, NULL)); ASSERT_EQUAL(memCacheSetBlockMod(memcache, user3, block1, 'U'), MEMCACHE_PERMISSION_DENIED); ASSERT_TRUE(checkBlock(block1, 10, 'A', user1, NULL)); memCacheDestroy(memcache); return true; } static bool memCacheTrustTest(void) { MemCache memcache = memCacheCreate(); ASSERT_NOT_NULL(memcache); char *user1 = "scorpion"; char *user2 = "tarakany"; char *user3 = "lumen000"; char *hacker = "rammstei"; ASSERT_SUCCESS(memCacheAddUser(memcache, user1, 4223)); ASSERT_SUCCESS(memCacheAddUser(memcache, user2, 4323)); ASSERT_SUCCESS(memCacheAddUser(memcache, user3, 4323)); ASSERT_SUCCESS(memCacheTrust(memcache, user1, user2)); ASSERT_SUCCESS(memCacheTrust(memcache, user1, user1)); ASSERT_SUCCESS(memCacheTrust(memcache, user1, user3)); ASSERT_SUCCESS(memCacheUntrust(memcache, user1, user3)); ASSERT_EQUAL(memCacheTrust(memcache, hacker, user2), MEMCACHE_USER_NOT_FOUND); ASSERT_EQUAL(memCacheTrust(memcache, user1, hacker), MEMCACHE_USER_NOT_FOUND); void *blockU = memCacheAllocate(memcache, user1, 42); ASSERT_TRUE(checkBlock(blockU, 42, 'U', user1, NULL)); void *blockG = memCacheAllocate(memcache, user1, 23); ASSERT_TRUE(checkBlock(blockG, 23, 'U', user1, NULL)); ASSERT_EQUAL(memCacheSetBlockMod(memcache, user2, blockG, 'G'), MEMCACHE_PERMISSION_DENIED); ASSERT_SUCCESS(memCacheSetBlockMod(memcache, user1, blockG, 'G')); ASSERT_TRUE(checkBlock(blockG, 23, 'G', user1, NULL)); void *blockA = memCacheAllocate(memcache, user1, 23); ASSERT_TRUE(checkBlock(blockA, 23, 'U', user1, NULL)); ASSERT_EQUAL(memCacheSetBlockMod(memcache, user2, blockA, 'A'), MEMCACHE_PERMISSION_DENIED); ASSERT_SUCCESS(memCacheSetBlockMod(memcache, user1, blockA, 'A')); ASSERT_TRUE(checkBlock(blockA, 23, 'A', user1, NULL)); ASSERT_EQUAL(memCacheFree(memcache, hacker, blockU), MEMCACHE_USER_NOT_FOUND); ASSERT_EQUAL(memCacheFree(memcache, hacker, blockG), MEMCACHE_USER_NOT_FOUND); ASSERT_EQUAL(memCacheFree(memcache, hacker, blockA), MEMCACHE_USER_NOT_FOUND); ASSERT_EQUAL(memCacheFree(memcache, user3, blockU), MEMCACHE_PERMISSION_DENIED); ASSERT_EQUAL(memCacheFree(memcache, user3, blockG), MEMCACHE_PERMISSION_DENIED); ASSERT_SUCCESS(memCacheFree(memcache, user3, blockA)); ASSERT_EQUAL(memCacheFree(memcache, user2, blockU), MEMCACHE_PERMISSION_DENIED); ASSERT_SUCCESS(memCacheFree(memcache, user2, blockG)); ASSERT_EQUAL(memCacheFree(memcache, user2, blockA), MEMCACHE_BLOCK_NOT_ALLOCATED); ASSERT_SUCCESS(memCacheFree(memcache, user1, blockU)); ASSERT_EQUAL(memCacheFree(memcache, hacker, blockG), MEMCACHE_USER_NOT_FOUND); ASSERT_EQUAL(memCacheFree(memcache, hacker, blockA), MEMCACHE_USER_NOT_FOUND); memCacheDestroy(memcache); return true; } static bool memCacheUntrustTest(void) { MemCache memcache = memCacheCreate(); ASSERT_NOT_NULL(memcache); //users char * user1 = "gammaray"; char * user2 = "scorpion"; char * user3 = "amaranth"; char * user4 = "radiohea"; // add users to system ASSERT_SUCCESS(memCacheAddUser(memcache, user1, 100)); ASSERT_SUCCESS(memCacheAddUser(memcache, user2, 100)); ASSERT_SUCCESS(memCacheAddUser(memcache, user3, 100)); ASSERT_SUCCESS(memCacheAddUser(memcache, user4, 100)); // trusting ASSERT_SUCCESS(memCacheTrust(memcache, user1, user2)); ASSERT_SUCCESS(memCacheTrust(memcache, user2, user1)); ASSERT_SUCCESS(memCacheTrust(memcache, user4, user4)); ASSERT_SUCCESS(memCacheTrust(memcache, user4, user4)); // allocations void *block1U1 = memCacheAllocate(memcache, user1, 23); ASSERT_NOT_NULL(block1U1); ASSERT_TRUE(checkBlock(block1U1, 23, 'U', user1, NULL)); void *block1G1 = memCacheAllocate(memcache, user1, 42); ASSERT_NOT_NULL(block1G1); ASSERT_TRUE(checkBlock(block1G1, 42, 'U', user1, NULL)); void *block1A1 = memCacheAllocate(memcache, user1, 13); ASSERT_NOT_NULL(block1A1); ASSERT_TRUE(checkBlock(block1A1, 13, 'U', user1, NULL)); void *block2U1 = memCacheAllocate(memcache, user2, 23); ASSERT_NOT_NULL(block2U1); ASSERT_TRUE(checkBlock(block2U1, 23, 'U', user2, NULL)); void *block2G1 = memCacheAllocate(memcache, user2, 42); ASSERT_NOT_NULL(block2G1); ASSERT_TRUE(checkBlock(block2G1, 42, 'U', user2, NULL)); void *block2A1 = memCacheAllocate(memcache, user2, 13); ASSERT_NOT_NULL(block2A1); ASSERT_TRUE(checkBlock(block2A1, 13, 'U', user2, NULL)); void *block4U1 = memCacheAllocate(memcache, user4, 23); // untrusting ASSERT_SUCCESS(memCacheUntrust(memcache, user1, user2)); ASSERT_SUCCESS(memCacheUntrust(memcache, user4, user4)); ASSERT_SUCCESS(memCacheUntrust(memcache, user4, user4)); // chmods ASSERT_SUCCESS(memCacheSetBlockMod(memcache, user1, block1G1, 'G')); ASSERT_TRUE(checkBlock(block1G1, 42, 'G', user1, NULL)); ASSERT_SUCCESS(memCacheSetBlockMod(memcache, user1, block1A1, 'A')); ASSERT_TRUE(checkBlock(block1A1, 13, 'A', user1, NULL)); ASSERT_SUCCESS(memCacheSetBlockMod(memcache, user2, block2G1, 'G')); ASSERT_TRUE(checkBlock(block2G1, 42, 'G', user2, NULL)); ASSERT_SUCCESS(memCacheSetBlockMod(memcache, user2, block2A1, 'A')); ASSERT_TRUE(checkBlock(block2A1, 13, 'A', user2, NULL)); // frees ASSERT_EQUAL(memCacheFree(memcache, user1, block2U1), MEMCACHE_PERMISSION_DENIED); ASSERT_SUCCESS(memCacheFree(memcache, user1, block2G1)); ASSERT_SUCCESS(memCacheFree(memcache, user1, block2A1)); ASSERT_EQUAL(memCacheFree(memcache, user2, block1U1), MEMCACHE_PERMISSION_DENIED); ASSERT_EQUAL(memCacheFree(memcache, user2, block1G1), MEMCACHE_PERMISSION_DENIED); ASSERT_SUCCESS(memCacheFree(memcache, user2, block1A1)); ASSERT_SUCCESS(memCacheFree(memcache, user4, block4U1)); memCacheDestroy(memcache); return true; } static bool memCacheAllocateTest(void) { MemCache memcache = memCacheCreate(); ASSERT_NOT_NULL(memcache); //users char * user1 = "gammaray"; char * user2 = "scorpion"; char * user3 = "amaranth"; char * user4 = "nightwis"; // add users to system ASSERT_SUCCESS(memCacheAddUser(memcache, user1, 256)); ASSERT_SUCCESS(memCacheAddUser(memcache, user2, 266)); ASSERT_SUCCESS(memCacheAddUser(memcache, user3, 300)); ASSERT_NULL(memCacheAllocate(NULL, NULL, 0)); ASSERT_NULL(memCacheAllocate(memcache, NULL, 0)); ASSERT_NULL(memCacheAllocate(memcache, "user", 0)); ASSERT_NULL(memCacheAllocate(memcache, user4, 0)); ASSERT_NULL(memCacheAllocate(memcache, user1, 0)); ASSERT_NULL(memCacheAllocate(memcache, user1, -1)); ASSERT_NULL(memCacheAllocate(memcache, user1, 257)); void *block11 = memCacheAllocate(memcache, user1, 256); ASSERT_NOT_NULL(block11); ASSERT_TRUE(checkBlock(block11, 256, 'U', user1, NULL)); ASSERT_NULL(memCacheAllocate(memcache, user1, 1)); ASSERT_SUCCESS(memCacheSetBlockMod(memcache, user1, block11, 'A')); ASSERT_TRUE(checkBlock(block11, 256, 'A', user1, NULL)); ASSERT_SUCCESS(memCacheFree(memcache, user2, block11)); ASSERT_EQUAL(block11, memCacheGetFirstFreeBlock(memcache)); void *block21 = memCacheAllocate(memcache, user2, 256); ASSERT_EQUAL(block11, block21); ASSERT_TRUE(checkBlock(block21, 256, 'U', user2, NULL)); ASSERT_EQUAL(NULL, memCacheGetFirstFreeBlock(memcache)); ASSERT_SUCCESS(memCacheFree(memcache, user2, block21)); ASSERT_EQUAL(block21, memCacheGetFirstFreeBlock(memcache)); void *block22 = memCacheAllocate(memcache, user2, 256); ASSERT_EQUAL(block21, block22); ASSERT_TRUE(checkBlock(block22, 256, 'U', user2, NULL)); ASSERT_EQUAL(NULL, memCacheGetFirstFreeBlock(memcache)); void *block31 = memCacheAllocate(memcache, user3, 257); ASSERT_NOT_NULL(block31); ASSERT_SUCCESS(memCacheFree(memcache, user3, block31)); ASSERT_EQUAL(NULL, memCacheGetFirstFreeBlock(memcache)); memCacheDestroy(memcache); return true; } static bool memCacheFreeTest() { MemCache memcache = memCacheCreate(); ASSERT_NOT_NULL(memcache); //users char * user1 = "gammaray"; char * user2 = "scorpion"; char * user3 = "amaranth"; char * user4 = "nightwis"; // add users to system ASSERT_SUCCESS(memCacheAddUser(memcache, user1, 3*(1+257)*257/2)); ASSERT_SUCCESS(memCacheAddUser(memcache, user2, 266)); ASSERT_SUCCESS(memCacheAddUser(memcache, user3, 300)); // relations ASSERT_SUCCESS(memCacheTrust(memcache, user1, user2)); ASSERT_SUCCESS(memCacheTrust(memcache, user1, user3)); ASSERT_SUCCESS(memCacheUntrust(memcache, user1, user3)); ASSERT_EQUAL(memCacheFree(memcache, user1, NULL), MEMCACHE_BLOCK_NOT_ALLOCATED); for(int size = 4; size <= 257; ++size) { void *block1 = NULL, *block2 = NULL, *block3 = NULL; ASSERT_NOT_NULL(block1 = memCacheAllocate(memcache, user1, size)); ASSERT_NOT_NULL(block2 = memCacheAllocate(memcache, user1, size)); ASSERT_NOT_NULL(block3 = memCacheAllocate(memcache, user1, size)); ASSERT_TRUE(checkBlock(block1, size, 'U', user1, NULL)); ASSERT_TRUE(checkBlock(block2, size, 'U', user1, NULL)); ASSERT_TRUE(checkBlock(block2, size, 'U', user1, NULL)); char *fake_block = (char*)calloc(sizeof(int)+1+1+8+2+size+1, sizeof(char)); ASSERT_NOT_NULL(fake_block); *(int*)fake_block = size; *(fake_block+sizeof(int)+1) = 'U'; strcpy(fake_block+sizeof(int)+1+1, user1); ASSERT_TRUE(checkBlock(fake_block+sizeof(int)+1+1+8+2, size, 'U', user1, NULL)); ASSERT_EQUAL(memCacheFree(memcache, user4, fake_block), MEMCACHE_USER_NOT_FOUND); ASSERT_EQUAL(memCacheFree(memcache, user2, fake_block), MEMCACHE_BLOCK_NOT_ALLOCATED); ASSERT_EQUAL(memCacheFree(memcache, user1, fake_block+sizeof(int)+1+1+8+2), MEMCACHE_BLOCK_NOT_ALLOCATED); free(fake_block); ASSERT_SUCCESS(memCacheSetBlockMod(memcache, user1, block2, 'G')); ASSERT_SUCCESS(memCacheSetBlockMod(memcache, user1, block3, 'A')); ASSERT_TRUE(checkBlock(block1, size, 'U', user1, NULL)); ASSERT_TRUE(checkBlock(block2, size, 'G', user1, NULL)); ASSERT_TRUE(checkBlock(block3, size, 'A', user1, NULL)); sprintf(block1, "0%d", size); sprintf(block2, "1%d", size); sprintf(block3, "2%d", size); ASSERT_EQUAL(memCacheFree(memcache, user4, block1), MEMCACHE_USER_NOT_FOUND); ASSERT_EQUAL(memCacheFree(memcache, user3, block1), MEMCACHE_PERMISSION_DENIED); ASSERT_EQUAL(memCacheFree(memcache, user2, block1), MEMCACHE_PERMISSION_DENIED); ASSERT_SUCCESS(memCacheFree(memcache, user1, block1)); ASSERT_EQUAL(memCacheFree(memcache, user1, block1), MEMCACHE_BLOCK_NOT_ALLOCATED); ASSERT_EQUAL(memCacheFree(memcache, user4, block2), MEMCACHE_USER_NOT_FOUND); ASSERT_EQUAL(memCacheFree(memcache, user3, block2), MEMCACHE_PERMISSION_DENIED); ASSERT_SUCCESS(memCacheFree(memcache, user2, block2)); ASSERT_EQUAL(memCacheFree(memcache, user2, block2), MEMCACHE_BLOCK_NOT_ALLOCATED); ASSERT_EQUAL(memCacheFree(memcache, user4, block3), MEMCACHE_USER_NOT_FOUND); ASSERT_SUCCESS(memCacheFree(memcache, user3, block3)); ASSERT_EQUAL(memCacheFree(memcache, user3, block3), MEMCACHE_BLOCK_NOT_ALLOCATED); } int cnt[3][256] = {{0}}; MEMCACHE_FREE_FOREACH(block, memcache) { int modeIndex = *(char*)block - '0'; ASSERT_TRUE(0 <= modeIndex && modeIndex < 3); int size = (int)strtoimax((char*)block+1, NULL, 10); ASSERT_TRUE(1 <= size && size <= 256); char mod = modeIndex == 0 ? 'U' : modeIndex == 1 ? 'G' : 'A'; char data[10]; sprintf(data, "%d%d", modeIndex, size); ASSERT_TRUE(checkBlock(block, size, mod, user1, data)); ++cnt[modeIndex][size-1]; } for (int modeIndex = 0; modeIndex < 3; ++modeIndex) { for (int size = 4; size <= 256; ++size) { ASSERT_TRUE(cnt[modeIndex][size-1] == 1); } } memCacheDestroy(memcache); return true; } static bool memCacheAllocatedBlockForeachTest() { // NULL stable ASSERT_NULL(memCacheGetFirstAllocatedBlock(NULL)); ASSERT_NULL(memCacheGetCurrentAllocatedBlock(NULL)); ASSERT_NULL(memCacheGetNextAllocatedBlock(NULL)); MemCache memcache = memCacheCreate(); ASSERT_NOT_NULL(memcache); // empty test ASSERT_NULL(memCacheGetFirstAllocatedBlock(memcache)); ASSERT_NULL(memCacheGetCurrentAllocatedBlock(memcache)); ASSERT_NULL(memCacheGetNextAllocatedBlock(memcache)); // users char * user = "oomph123"; // add to system const int MODULO = 1024; const int MAX_SIZE = 1024 * 2; ASSERT_SUCCESS(memCacheAddUser(memcache, user, 6*(1+MAX_SIZE)*MAX_SIZE/2)); // allocations void *allocatedBlocks[3][MAX_SIZE], *freeBlocks[3][MAX_SIZE]; int visited[3][MAX_SIZE]; for (int size = 1; size <= MAX_SIZE; ++size) { for (int i = 0; i < 3; ++i) { visited[i][size-1] = 0; } ASSERT_NOT_NULL(allocatedBlocks[0][size-1] = memCacheAllocate(memcache, user, size)); ASSERT_TRUE(checkBlock(allocatedBlocks[0][size-1], size, 'U', user, NULL)); ASSERT_NOT_NULL(freeBlocks[0][size-1] = memCacheAllocate(memcache, user, size)); ASSERT_TRUE(checkBlock(freeBlocks[0][size-1], size, 'U', user, NULL)); ASSERT_NOT_NULL(allocatedBlocks[1][size-1] = memCacheAllocate(memcache, user, size)); ASSERT_TRUE(checkBlock(allocatedBlocks[1][size-1], size, 'U', user, NULL)); ASSERT_SUCCESS(memCacheSetBlockMod(memcache, user, allocatedBlocks[1][size-1], 'G')); ASSERT_TRUE(checkBlock(allocatedBlocks[1][size-1], size, 'G', user, NULL)); ASSERT_NOT_NULL(freeBlocks[1][size-1] = memCacheAllocate(memcache, user, size)); ASSERT_TRUE(checkBlock(freeBlocks[1][size-1], size, 'U', user, NULL)); ASSERT_SUCCESS(memCacheSetBlockMod(memcache, user, freeBlocks[1][size-1], 'G')); ASSERT_TRUE(checkBlock(freeBlocks[1][size-1], size, 'G', user, NULL)); ASSERT_NOT_NULL(allocatedBlocks[2][size-1] = memCacheAllocate(memcache, user, size)); ASSERT_TRUE(checkBlock(allocatedBlocks[2][size-1], size, 'U', user, NULL)); ASSERT_SUCCESS(memCacheSetBlockMod(memcache, user, allocatedBlocks[2][size-1], 'A')); ASSERT_TRUE(checkBlock(allocatedBlocks[2][size-1], size, 'A', user, NULL)); ASSERT_NOT_NULL(freeBlocks[2][size-1] = memCacheAllocate(memcache, user, size)); ASSERT_TRUE(checkBlock(freeBlocks[2][size-1], size, 'U', user, NULL)); ASSERT_SUCCESS(memCacheSetBlockMod(memcache, user, freeBlocks[2][size-1], 'A')); ASSERT_TRUE(checkBlock(freeBlocks[2][size-1], size, 'A', user, NULL)); } for (int size = 1; size <= MAX_SIZE; ++size) { for (int i = 0; i < 3; ++i) { ASSERT_SUCCESS(memCacheFree(memcache, user, freeBlocks[i][size-1])); } } int currentReminder = 0; MEMCACHE_ALLOCATED_FOREACH(block, memcache) { ASSERT_TRUE((uintptr_t)block % MODULO >= currentReminder); currentReminder = (uintptr_t)block % MODULO; bool found = false; for (int mod = 0; mod < 3 && !found; ++mod) { for (int size = 1; size <= MAX_SIZE && !found; ++size) { if (allocatedBlocks[mod][size-1] == block) { ++visited[mod][size-1]; found = true; } } } ASSERT_TRUE(found); } for (int size = 1; size <= MAX_SIZE; ++size) { for (int i = 0; i < 3; ++i) { ASSERT_EQUAL(visited[i][size-1], 1); } } ASSERT_NULL(memCacheGetCurrentAllocatedBlock(memcache)); ASSERT_NULL(memCacheGetNextAllocatedBlock(memcache)); memCacheDestroy(memcache); return true; } static bool memCacheFreeTest2(void) { MemCache memcache = memCacheCreate(); ASSERT_NOT_NULL(memcache); const int size = 50; char *user = "ironmaid"; char *content1 = "block1 of ironmaid"; char *content2 = "block2 of ironmaid"; ASSERT_SUCCESS(memCacheAddUser(memcache, user, 2*size)); void *block1 = memCacheAllocate(memcache, user, size); ASSERT_TRUE(checkBlock(block1, size, 'U', user, NULL)); void *block2 = memCacheAllocate(memcache, user, size); ASSERT_TRUE(checkBlock(block1, size, 'U', user, NULL)); sprintf(block1, content1); ASSERT_TRUE(checkBlock(block1, size, 'U', user, content1)); sprintf(block2, content2); ASSERT_TRUE(checkBlock(block2, size, 'U', user, content2)); ASSERT_SUCCESS(memCacheSetBlockMod(memcache, user, block1, 'A')); ASSERT_TRUE(checkBlock(block1, size, 'A', user, content1)); ASSERT_SUCCESS(memCacheSetBlockMod(memcache, user, block2, 'G')); ASSERT_TRUE(checkBlock(block2, size, 'G', user, content2)); ASSERT_SUCCESS(memCacheFree(memcache, user, block1)); ASSERT_SUCCESS(memCacheFree(memcache, user, block2)); ASSERT_TRUE(checkBlock(memCacheGetFirstFreeBlock(memcache), size, 'A', user, content1) || checkBlock(memCacheGetFirstFreeBlock(memcache), size, 'G', user, content2)); ASSERT_TRUE(memCacheGetFirstFreeBlock(memcache) == block1 || memCacheGetFirstFreeBlock(memcache) == block2); memCacheDestroy(memcache); return true; } static bool memCacheFreeTest3(void) { MemCache memcache = memCacheCreate(); ASSERT_NOT_NULL(memcache); const int size = 50; char *user1 = "ironmaid"; char *user2 = "edguy423"; char *user3 = "paradise"; char *content1 = "block1 of ironmaid"; char *content2 = "block2 of ironmaid"; ASSERT_SUCCESS(memCacheAddUser(memcache, user1, 2*size)); ASSERT_SUCCESS(memCacheAddUser(memcache, user2, 2*size)); ASSERT_SUCCESS(memCacheAddUser(memcache, user3, 2*size)); ASSERT_SUCCESS(memCacheTrust(memcache, user1, user3)); void *block1 = memCacheAllocate(memcache, user1, size); ASSERT_TRUE(checkBlock(block1, size, 'U', user1, NULL)); void *block2 = memCacheAllocate(memcache, user1, size); ASSERT_TRUE(checkBlock(block1, size, 'U', user1, NULL)); sprintf(block1, content1); ASSERT_TRUE(checkBlock(block1, size, 'U', user1, content1)); sprintf(block2, content2); ASSERT_TRUE(checkBlock(block2, size, 'U', user1, content2)); ASSERT_SUCCESS(memCacheSetBlockMod(memcache, user1, block1, 'A')); ASSERT_TRUE(checkBlock(block1, size, 'A', user1, content1)); ASSERT_SUCCESS(memCacheSetBlockMod(memcache, user1, block2, 'G')); ASSERT_TRUE(checkBlock(block2, size, 'G', user1, content2)); ASSERT_SUCCESS(memCacheFree(memcache, user2, block1)); ASSERT_SUCCESS(memCacheFree(memcache, user3, block2)); ASSERT_TRUE(checkBlock(memCacheGetFirstFreeBlock(memcache), size, 'A', user1, content1) || checkBlock(memCacheGetFirstFreeBlock(memcache), size, 'G', user1, content2)); ASSERT_TRUE(memCacheGetFirstFreeBlock(memcache) == block1 || memCacheGetFirstFreeBlock(memcache) == block2); memCacheDestroy(memcache); return true; } static bool memCacheFreeBlockForeachTest(void) { // NULL stable ASSERT_NULL(memCacheGetCurrentFreeBlock(NULL)); ASSERT_NULL(memCacheGetFirstFreeBlock(NULL)); ASSERT_NULL(memCacheGetNextFreeBlock(NULL)); MemCache memcache = memCacheCreate(); ASSERT_NOT_NULL(memcache); // empty stable ASSERT_NULL(memCacheGetCurrentFreeBlock(NULL)); ASSERT_NULL(memCacheGetFirstFreeBlock(NULL)); ASSERT_NULL(memCacheGetNextFreeBlock(NULL)); //users char *user1 = "accept12"; char *user2 = "offsprin"; char *user3 = "nightwis"; char *user4 = "johndoe1"; // add to system const int MAX_SIZE = 258; const int MEMORY_LIMIT = (1+MAX_SIZE) * MAX_SIZE / 2; ASSERT_SUCCESS(memCacheAddUser(memcache, user1, MEMORY_LIMIT)); ASSERT_SUCCESS(memCacheAddUser(memcache, user2, MEMORY_LIMIT)); ASSERT_SUCCESS(memCacheAddUser(memcache, user3, MEMORY_LIMIT)); ASSERT_SUCCESS(memCacheAddUser(memcache, user4, MEMORY_LIMIT)); // trusts ASSERT_SUCCESS(memCacheTrust(memcache, user2, user4)); //Empty cache ASSERT_NULL(memCacheGetCurrentFreeBlock(memcache)); ASSERT_NULL(memCacheGetFirstFreeBlock(memcache)); ASSERT_NULL(memCacheGetNextFreeBlock(memcache)); // allocate blocks void *user1Blocks[258] = {NULL}, *user2Blocks[258] = {NULL}, *user3Blocks[258] = {NULL}, *user4Blocks[258] = {NULL}; for (int size = 1; size <= 258; ++size) { ASSERT_NOT_NULL(user1Blocks[size-1] = memCacheAllocate(memcache, user1, size)); ASSERT_TRUE(checkBlock(user1Blocks[size-1], size, 'U', user1, NULL)); ASSERT_NOT_NULL(user2Blocks[size-1] = memCacheAllocate(memcache, user2, size)); ASSERT_TRUE(checkBlock(user2Blocks[size-1], size, 'U', user2, NULL)); ASSERT_SUCCESS(memCacheSetBlockMod(memcache, user2, user2Blocks[size-1], 'G')); ASSERT_TRUE(checkBlock(user2Blocks[size-1], size, 'G', user2, NULL)); ASSERT_NOT_NULL(user3Blocks[size-1] = memCacheAllocate(memcache, user3, size)); ASSERT_SUCCESS(memCacheSetBlockMod(memcache, user3, user3Blocks[size-1], 'A')); ASSERT_TRUE(checkBlock(user3Blocks[size-1], size, 'A', user3, NULL)); ASSERT_NOT_NULL(user4Blocks[size-1] = memCacheAllocate(memcache, user4, size)); } // deallocate blocks void *freedBlocks[3*256]; int visited[3*256] = {0}; for (int size = 1; size <= 256; ++size) { ASSERT_SUCCESS(memCacheFree(memcache, user1, user1Blocks[size-1])); freedBlocks[3*(size-1)] = user1Blocks[size-1]; ASSERT_SUCCESS(memCacheFree(memcache, user4, user2Blocks[size-1])); freedBlocks[3*(size-1)+1] = user2Blocks[size-1]; ASSERT_EQUAL(memCacheFree(memcache, user2, user2Blocks[size-1]), MEMCACHE_BLOCK_NOT_ALLOCATED); ASSERT_SUCCESS(memCacheFree(memcache, user4, user3Blocks[size-1])); freedBlocks[3*(size-1)+2] = user3Blocks[size-1]; } ASSERT_SUCCESS(memCacheFree(memcache, user1, user1Blocks[257-1])); ASSERT_SUCCESS(memCacheFree(memcache, user4, user2Blocks[257-1])); ASSERT_SUCCESS(memCacheFree(memcache, user4, user3Blocks[257-1])); int currentSize = 1, blocksOfCurrentSize = 0; MEMCACHE_FREE_FOREACH(block, memcache) { for (int i = 0; i < 3 * 256; ++i) { if (freedBlocks[i] == block) { ++visited[i]; int size = i / 3 + 1; ASSERT_EQUAL(size, currentSize); } } if (++blocksOfCurrentSize == 3) { ++currentSize; blocksOfCurrentSize = 0; } } ASSERT_EQUAL(currentSize, 257); ASSERT_EQUAL(blocksOfCurrentSize, 0); for (int i = 0; i < 3 * 256; ++i) { ASSERT_EQUAL(visited[i], 1); } memCacheDestroy(memcache); return true; } static bool memCacheResetTest(void) { MemCache memcache = memCacheCreate(); ASSERT_NOT_NULL(memcache); char *user1 = "skillet1"; char *user2 = "forsaken"; ASSERT_SUCCESS(memCacheAddUser(memcache, user1, 42)); ASSERT_SUCCESS(memCacheAddUser(memcache, user2, 42)); ASSERT_SUCCESS(memCacheTrust(memcache, user1, user2)); void *block1 = memCacheAllocate(memcache, user1, 17); ASSERT_TRUE(checkBlock(block1, 17, 'U', user1, NULL)); void *block2 = memCacheAllocate(memcache, user1, 17); ASSERT_SUCCESS(memCacheSetBlockMod(memcache, user1, block2, 'G')); ASSERT_TRUE(checkBlock(block2, 17, 'G', user1, NULL)); ASSERT_EQUAL(memCacheReset(NULL), MEMCACHE_NULL_ARGUMENT); ASSERT_SUCCESS(memCacheReset(memcache)); ASSERT_NULL(memCacheAllocate(memcache, user1, 1)); ASSERT_EQUAL(memCacheFree(memcache, user1, block1), MEMCACHE_USER_NOT_FOUND); ASSERT_SUCCESS(memCacheAddUser(memcache, user1, 42)); ASSERT_SUCCESS(memCacheAddUser(memcache, user2, 42)); ASSERT_EQUAL(memCacheFree(memcache, user1, block1), MEMCACHE_BLOCK_NOT_ALLOCATED); block2 = memCacheAllocate(memcache, user1, 42); ASSERT_SUCCESS(memCacheSetBlockMod(memcache, user1, block2, 'G')); ASSERT_TRUE(checkBlock(block2, 42, 'G', user1, NULL)); ASSERT_EQUAL(memCacheFree(memcache, user2, block2), MEMCACHE_PERMISSION_DENIED); memCacheDestroy(memcache); return true; } int main() { setvbuf(stdout, NULL, _IONBF, 0); setvbuf(stderr, NULL, _IONBF, 0); RUN_TEST(memCacheExampleTest); RUN_TEST(memCacheCreateTest); RUN_TEST(memCacheDestroyTest); RUN_TEST(memCacheAddUserTest); RUN_TEST(memCacheSetBlockModTest); RUN_TEST(memCacheTrustTest); RUN_TEST(memCacheUntrustTest); RUN_TEST(memCacheAllocateTest); RUN_TEST(memCacheFreeTest); RUN_TEST(memCacheFreeTest2); RUN_TEST(memCacheFreeTest3); RUN_TEST(memCacheAllocatedBlockForeachTest); RUN_TEST(memCacheFreeBlockForeachTest); RUN_TEST(memCacheResetTest); return 0; }
C
#include <math.h> #include <stdlib.h> #include <stdio.h> #include "api.h" #define REAL 0 #define IMAG 1 static double evm(complex symbol, complex ref) { double real_diff = pow(symbol[REAL] - ref[REAL], 2); double imag_diff = pow(symbol[IMAG] - ref[IMAG], 2); return sqrt(real_diff + imag_diff); } static char gray_map[] = {0, 1, 3, 2}; complex *frequency_shift(double *input, double fc, double fs, int N) { complex *output = (complex *) malloc(N * sizeof(complex)); for (int i = 0; i < N; i++) { output[i][REAL] = input[i] * cos((2 * M_PI * fc * i * 1.0) / fs); output[i][IMAG] = -input[i] * sin((2 * M_PI * fc * i * 1.0) / fs); } return output; } double qpsk_demodulator(complex symbol, double constellation_offset, char *decoded_symbol) { complex ref_point[4]; for (int i = 0; i < 4; i++) { ref_point[i][REAL] = cos(constellation_offset + i * M_PI / 2); ref_point[i][IMAG] = sin(constellation_offset + i * M_PI / 2); } double min_offset = evm(symbol, ref_point[0]); int min_index = 0; for (int i = 1; i < 4; i++) { double tmp = evm(symbol, ref_point[i]); if (tmp < min_offset) { min_offset = tmp; min_index = i; } } *decoded_symbol = gray_map[min_index]; return min_offset; } #define PREAMBLE_LENGTH 8 #define PREAMBLE_BYTE 0xa5 #define BITS_IN_STREAM 2 char *bitstream_to_bytestream(char *bitstream, int length) { int bytelen = length / 4; char *bytestream = (char *) malloc(bytelen); int byte_cnt = 0; char curr_byte = 0; int bits_cnt = 0; for (int i = 0; i < length; i++) { curr_byte |= (bitstream[i] << (BITS_IN_STREAM * (3 - bits_cnt))); bits_cnt++; if (bits_cnt == 8 / BITS_IN_STREAM) { bits_cnt = 0; bytestream[byte_cnt++] = curr_byte; curr_byte = 0; } } return bytestream; } void frame_sync(char **bytestream, int length) { int cnt = 0; for (int i = 0; i < length; i++) { if (cnt == PREAMBLE_LENGTH) { // preamble detected *bytestream = &(*bytestream[i - cnt]); break; } if (*bytestream[i] == PREAMBLE_BYTE && cnt < PREAMBLE_LENGTH) { cnt++; } else if (*bytestream[i] != PREAMBLE_BYTE && cnt < PREAMBLE_LENGTH) { cnt = 0; } } } void frame_step(char **bytestream, int frame_length) { *bytestream += frame_length; } int frame_decoder(char *bytestream, char **data) { bytestream += PREAMBLE_LENGTH; // skip preamble int len = *(bytestream++); // get packet length and move to data if (len <= 0) { printf("Invalid length"); exit(1); } *data = (char *) malloc(len + 1); (*data)[len] = 0; for (int i = 0; i < len; i++) { (*data)[i] = bytestream[i]; } return len + PREAMBLE_LENGTH * 2 + 2 + 1; } double *ofdm_demodulator(complex *spectrum, int *carrier_idx, int carrier_no, char **data) { *data = (char *) malloc(carrier_no); double *evm = (double *) malloc(sizeof(double) * carrier_no); int cnt = 0; for (int i = 0; i < carrier_no; i++) { char tmp; evm[i] = qpsk_demodulator(spectrum[carrier_idx[i]], M_PI / 4, &tmp); (*data)[i] = tmp; } return evm; } unsigned short crc16_check(char *msg, int length) { int counter; unsigned short crc = CRC16_START_VAL; for (counter = 0; counter < length; counter++) { crc = (crc<<8) ^ crc16tab[((crc>>8) ^ *(char *)msg++)&0x00FF]; } return crc; } int frame_decoder_valid(char *bytestream, char **data, bool *valid) { int len = frame_decoder(bytestream, data); len -= 2 * PREAMBLE_LENGTH + 2 + 1; // message length without 2 bytes for CRC hash unsigned short crc = crc16_check(*data, len); // crc from message unsigned short msg_crc = 0; msg_crc |= bytestream[PREAMBLE_LENGTH + 1 + len] & 0xFF; msg_crc = (msg_crc << 8); msg_crc |= bytestream[PREAMBLE_LENGTH + 1 + len + 1] & 0xFF; *valid = msg_crc == crc; return len += 2 * PREAMBLE_LENGTH + 2 + 1; }
C
#include<stdio.h> #include<stdlib.h> #include"busdetails.c" #include"decleration.c" #include<strings.h> struct busdetails person[300]; int count=0; int id2=1000; int main() { int **seat,choice,price=500,slection,i; seat=(int **)calloc(101,sizeof(int *)); for (i=0;i<3;i++) *(seat+i)=(int *)calloc(101,sizeof(int )); int x; while(x!=5) { choice=choice1(); switch(choice) { case 1: price=changeprize(price); break; case 2: details(); break; case 3: slection=ticket(); reservation(seat[slection-1],price,slection); count++; break; case 4: slection=cticket(); cancel(seat[slection-1]); break; case 5: x=5; break; default: printf("Choice not available\n"); break; } } } int changeprize(int prize) { char pass[10],pak[10]="pass"; printf("Enter the password to change price of ticket: "); scanf("%s",pass); if (strcmp(pass,pak)==0) { printf("Please enter new price: "); scanf("%d",&prize); } else printf("The entered password is wrong! "); return prize; } void reservation(int *array,int price,int slection) { int i,j; printf("\n SEAT\n\n\n"); for (i=1;i<=48;i++) { if (array[i]==0) printf("%d\t",i); else printf("*\t",i); if(i%4==0) printf("\n\n"); } printf("\nPlease enter your name: "); scanf(" %19[^\n]%*[^\n]",&person[count].name); printf("\nPlease enter your phone number: "); scanf("%u",&person[count].phone); printf("\nWhich seat number you want? "); scanf("%d",&j); if (j>100||j<1) { printf("seat number is unavailable in this BUS\n"); printf("Please re-enter seat number: "); scanf("%d",&j); } if (array[j]==1) { printf("Sorry, this ticket is already booked! Please choose another seat.\n"); scanf("%d",&j); } else array[j]=1; person[count].seat=j; if (slection==1) ticket1(j,person[count].name,id2,price); else if (slection==2) ticket2(j,person[count].name,id2,price); else ticket3(j,person[count].name,id2,price); id2++; } int choice1(void) { int choice; printf("\n\n Dhaka To Tangail Ticket Booking System\n"); printf(" ==================================================================\n"); printf("|| 1.- To edit price of ticket (only admin): ||\n"); printf("|| 2.- To view reserved tickets (only admin): ||\n"); printf("|| 3.- To puchase ticket: ||\n"); printf("|| 4.- To cancel the seat: ||\n"); printf("|| 5.- Exit system: ||\n"); printf("||================================================================||\n"); printf(" Enter your choice: "); scanf("%d",&choice); return choice; } void cancel(int *array) { int Cseat,i,stop; printf("Please enter ID number of ticket: "); scanf("%d",&Cseat); for (i=0;i<300;i++) { if(Cseat==person[i].id) { stop=5; system("cls"); printf("%s your seat is %d cancelled",person[i].name,person[i].seat); array[person[i].seat]=0; i=300; } } if (stop!=5) printf("Ticket ID number is incorrect please enter right one to cancel ticket: \n"); } void ticket1(int choice,char name[10],int id2,int price) { system("cls"); printf("\n\n"); printf("\t-----------------Dhaka To Tangail BUS TICKET----------------\n"); printf("\t============================================================\n"); printf("\t Booking ID : %d \t\t\tBUS Name : Nirala Super\n",id2); printf("\t Customer : %s\n",name); printf("\t Date : 27-07-2019\n"); printf("\t Time : 08:00pm\n"); printf("\t Bus NO : 1101\n"); printf("\t seats No: %d \n",choice); printf("\t price .: %d \n\n",price); person[count].id=id2; printf("\t============================================================\n"); return; } void details(void) { int i; char pass[10],pak[10]="pass"; printf("Enter the password to see details: "); scanf("%s",&pass); if (strcmp(pass,pak)==0) { for (i=0;i<count;i++) { printf("seat no: %d is booked by %s booking id is %d\n",person[i].seat,person[i].name,person[i].id); } } else printf("Entered password is wrong \n"); } int ticket(void) { int i; system("cls"); printf("\t\t\twhich BUS you want to Travale?\n"); printf("\t\t\t----------------------------\n\n"); printf("\t\t\tpress 1 for Nirala Super\n\n"); printf("\t\t\tpress 2 for Drutogami \n\n"); printf("\t\t\tpress 3 for Binimoy \n"); scanf("%d",&i); system("cls"); return i; } void ticket2(int choice,char name[10],int id2,int price) { system("cls"); printf("\n\n"); printf("\t-----------------BUS BOOKING TICKET----------------\n"); printf("\t============================================================\n"); printf("\t Booking ID : %d \t\t\tBUS Name : Durtogami \n",id2); printf("\t Customer : %s\n",name); printf("\t\t\t Date : 15-04-2019\n"); printf("\t Time : 09:00pm\n"); printf("\t Bus NO : 1101\n"); printf("\t seats No. : %d \n",choice); printf("\t price . : %d \n\n",price); person[count].id=id2; printf("\t============================================================\n"); return; } int cticket(void) { int i; printf("\t\t\twhich BUS ticket you want to cancel\n"); printf("\t\t\t-------------------------------------\n"); printf("\t\t\tpress 1 Nirala Super\n\n"); printf("\t\t\tpress 2 for Drutogami\n\n"); printf("\t\t\tpress 3 for Binimoy\n"); scanf("%d",&i); return i; } void ticket3(int choice,char name[10],int id2,int price) { system("cls"); printf("\n\n"); printf("\t-----------------BUS BOOKING TICKET----------------\n"); printf("\t============================================================\n"); printf("\t Booking ID : %d \t\t\t BUS Name : Binimoy\n",id2); printf("\t Customer : %s\n",name); printf("\t\t\t Date : 5-07-2019\n"); printf("\t Time : 10:00pm\n"); printf("\t Bus NO : 1104\n"); printf("\t seats No. : %d \n",choice); printf("\t price . : %d \n\n",price); person[count].id=id2; printf("\t============================================================\n"); return; }
C
/* ** command_center.c for 42sh in /home/somasu_b/rendu/mysh/src ** ** Made by somasu_b ** Login <[email protected]> ** ** Started on Fri May 16 01:40:44 2014 somasu_b ** Last update Sun Jun 1 19:50:04 2014 somasu_b */ #include <unistd.h> #include <stdlib.h> #include <string.h> #include "sh.h" static int isprintable(char *str) { int i; i = 0; while (str[i]) if (str[i] < ' ' || str[i++] > '~') return (-1); return (1); } static int replace_tild(t_tok *cmd, t_env *env) { char *str; t_env *tmp; tmp = env->next; while (tmp != env && strcmp("HOME", tmp->var) != 0) tmp = tmp->next; if (tmp == env) return (0); if ((str = malloc(sizeof(*str) * (strlen(cmd->cmd) + strlen(tmp->contents) + 1))) == NULL) return (-1); str[0] = '\0'; str = strcat(str, tmp->contents); str = strcat(str, (cmd->cmd) + 1); cmd->cmd = str; return (0); } static int replace_doll(t_tok *tmp, t_42 *sh) { t_env *save; t_vars *tmp2; save = sh->env->next; tmp2 = sh->vars->next; while (save != sh->env && strstr(tmp->cmd, save->var) == NULL) save = save->next; if (save == sh->env) { while ( tmp2 != sh->vars && strstr(tmp->cmd, tmp2->var) == NULL) tmp2 = tmp2->next; if (tmp2 != sh->vars) tmp->cmd = strdup(tmp2->contents); } else tmp->cmd = strdup(save->contents); return (0); } static int replacing(t_42 *sh, t_tok *cmd) { t_tok *tmp; tmp = cmd->next; while (tmp != cmd) { if (tmp->cmd[0] == '~') if (replace_tild(tmp, sh->env) == -1) return (-1); if (tmp->cmd[0] == '$') replace_doll(tmp, sh); tmp = tmp->next; } return (0); } int command_center(t_42 *sh, char *command) { t_tok *cmd_list; t_tree *cmd_tree; if (isprintable(command) == -1) return (1); if ((cmd_list = cmd_to_list(command)) == NULL) return (1); if (lexer(cmd_list) == -1) return (1); if (replacing(sh, cmd_list) == -1) return (1); if ((cmd_tree = parser(cmd_list)) == NULL) return (1); if (main_execution(sh, cmd_tree) == -1) return (-1); free_tree(cmd_tree); return (0); }
C
int a = 0, b = 0; struct Vector { unsigned size; unsigned capacity; int *data; }; int Init(struct Vector *V, unsigned capacity) { if (!V) { return -1; } V->data = malloc(sizeof(int) * capacity); if (!V->data) { return -1; } V->size = 0; V->capacity = capacity; return 0; } // int IsFull(const struct Vector *V) { // if (!V) { // return -1; // } // return V->size == V->capacity; // } int IsFull(const struct Vector * const V); // Comments test // Comments test int Push(struct Vector *V, int E) { if (!V) { return -1; } V->data[V->size++] = E; return 0; } // int main() { // struct Vector V, P; // Init(&V, 2); // return P.size; // } // int branch(int a, int b) { // if (a > 10 && b < 10) { // return 0; // } // return 1; // }
C
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #define NUM_THREADS 20 #define NUM_INCREMENT 100000 int counter; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *addThings(void *threadId) { for (int i = 0; i < NUM_INCREMENT; i++) { pthread_mutex_lock(&mutex); counter += 1; pthread_mutex_unlock(&mutex); } pthread_exit(NULL); } int main(int argc, char **argv) { pthread_t threads[NUM_THREADS]; long t; for (t = 0; t < NUM_THREADS; t++) { int rc = pthread_create(&threads[t], NULL, addThings, (void *)t); if (rc) { printf("ERROR; return code from pthread_create() is %d\n", rc); exit(1); } } for (t = 0; t < NUM_THREADS; t++) { pthread_join(threads[t], NULL); } printf("Final value of counter is: %d\n", counter); pthread_exit(NULL); }
C
#include "buffer.h" #include <stdlib.h> #include <alloca.h> #include <string.h> void sbuf_create(sbuf_t* sbuf, int max_length) { sbuf->data = NULL; sbuf->max_length = max_length; sbuf->data = (uint8_t*)malloc(max_length); if(sbuf->data == NULL) sbuf->max_length = 0; sbuf->length = 0; } void sbuf_reset(sbuf_t* sbuf) { sbuf->length = 0; } void sbuf_release(sbuf_t* sbuf) { sbuf->max_length = 0; sbuf->length = 0; free(sbuf->data); sbuf->data = NULL; } int sbuf_add_data(sbuf_t* sbuf, const void* data, int length) { if(length == 0) return 0; // Check for overflow: if(sbuf->length + length > sbuf->max_length) { return 0; } memcpy(sbuf->data + sbuf->length, data, length); sbuf->length += length; return sbuf->length; }
C
#include <stdio.h> #include <stdlib.h> void printnum(long n, void (*p)()){ if(n < 0){ printf("n is negative .\n"); (*p)('-'); n = -n; } if(n >= 10) printnum(n/10, p); (*p)("0123456789"[n % 10]); } void func(char c){ printf("%c\n",c); } int main(){ long x = -145l; printnum(x, (void (*)())func); // clever !!!!! return 0; }
C
#include "holberton.h" /** * _isalpha - returns if c is a letter or not * * @c: 1 is a letter, 0 is not * * Return: Ends program */ int _isalpha(int c) { if ((c >= 65 && c <= 90) || (c >= 97 && c <= 122)) return (1); else return (0); }
C
#include "sh61.h" #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <sys/wait.h> #include <libgen.h> static volatile sig_atomic_t SIGINT_RECEIVED = 0; //boolean for whether or not Cntrl+C has been received pid_t shell_pgid = 0; //pgid of the shell itself pid_t background_pgid = 10; //pgid of the background process, if any pid_t foreground_pgid = 20; //pgid for commands running in foreground, via start_command int pipe_fd_counter = 0; //counter of number of pipe file descriptors int pipefd[4][2]; //four pairs, which could be increased to the Linux maximum, for use here int end_of_pipe = 0; //boolean for whether end of pipe has been received // struct command // This an individual command, which is a node in the 1st dimension (i.e., row) of a linked list of linked lists typedef struct command command; struct command { int argc; //number of arguments char** argv; //arguments, terminated by NULL pid_t pid; //process ID running this command, -1 if none pid_t pgid; //process group ID of this command int background; //command should be run in the background (1) or not (0) int logical_and_condition; //records whether this is a conditional command (0 for yes, 1 for no) for an && statement int logical_or_condition; //records whether this is a conditional command (0 for yes, 1 for no) for an || statement int pipe_receiver; //records that this process is the reader from a pipe int pipe_sender; //records that this process is a writer to a pipe int type; //type of argument, specified by header file int file_in; //records whether there is a file redirected in char* file_in_name; //records the name of the file redirected in int file_out; //records whether there is a file redirected out char* file_out_name; //records the name of the file redirected out int file2_out; //records whether there is a file redirected out in place of stderr char* file2_out_name; //records the name of the file redirected out in place of stderr struct command* next; //pointer to the next single command in this command string }; // command_alloc() // Allocate and return a new command structure. // Initializes its data members static command* command_alloc(void) { command* c = (command*) malloc(sizeof(command)); c->argc = 0; c->argv = NULL; c->pid = -1; c->pgid = -1; c->background = 0; c->logical_and_condition = 0; c->logical_or_condition = 0; c->pipe_receiver = 0; c->pipe_sender = 0; c->type = TOKEN_NORMAL; c->file_in = 0; c->file_in_name = NULL; c->file_out = 0; c->file_out_name = NULL; c->file2_out = 0; c->file2_out_name = NULL; c->next = NULL; return c; } //struct commands // a column & 2nd dimension linked list of linked lists of commands, the // overall struct with data members necessary and named the same as those // of an individual node struct commands { int commands_count; pid_t pgid; int background; int logical_and_condition; int logical_or_condition; int pipe_receiver; int pipe_sender; int truth_status; command* top_cmd; struct command *command_head; //head of the column struct command *command_tail; //tail of the column struct command* command_curr; struct commands* next; }; struct commands *commands_beginning = NULL; //first in the row struct commands *commands_ending = NULL; //last in the row struct commands *commands_curr = NULL; //current column of command //create_commands // creates a column, a linked list of linked lists struct commands* create_commands(command* cmd) { struct commands *argp = (struct commands*)malloc(sizeof(struct commands)); if(NULL == argp) { printf("\n Node lcreation failed \n"); return NULL; } argp->commands_count = 0; argp->pgid = -1; argp->background = 0; argp->logical_and_condition = 0; argp->logical_or_condition = 0; argp->pipe_receiver = 0; argp->pipe_sender = 0; argp->truth_status = 1; argp->next = NULL; argp->command_head = cmd; argp->command_tail = cmd; commands_beginning = argp; commands_ending = argp; return argp; } // add_command // adds a command to a list (row) struct commands* add_command(command* cmd) { if(NULL == commands_beginning){ return (create_commands(cmd)); } commands_ending->command_tail->next = cmd; commands_ending->command_tail = cmd; commands_ending->background = cmd->background; return commands_ending; } // add_commands // adds a new column of commands struct commands* add_commands(command* cmd){ struct commands *argp = (struct commands*)malloc(sizeof(struct commands)); if(NULL == argp) { printf("\n Node creation failed \n"); return NULL; } argp->commands_count++; argp->pgid = cmd->pgid; argp->next = NULL; argp->command_head = cmd; argp->command_tail = cmd; commands_ending->next = argp; commands_ending = argp; return argp; } // command_free(c) // Free command structure `c`, including all its words. static void command_free(command* c) { for (int i = 0; i != c->argc; ++i) free(c->argv[i]); free(c->argv); if (c->file_in_name) free(c->file_in_name); if (c->file_out_name) free(c->file_out_name); if (c->file2_out_name) free(c->file2_out_name); free(c); } // free_command_column // frees a full column of commands (i.e., a commandS) void free_command_column(struct commands* commands) { struct command *argp = commands->command_head; struct command *prev; while (argp != NULL) { prev = argp; argp = argp->next; command_free(prev); } } // free_commands // frees a full row of commands void free_commands() { struct commands *argp = commands_beginning; struct commands *prev; while (argp != NULL) { prev = argp; argp = argp->next; free_command_column(prev); free(prev); } } // stat_file // checks whether a file exists int stat_file(const char* file_name){ struct stat file_status; int file_exists = stat(file_name, &file_status); if (file_exists == -1) return 0; else return 1; } // command_append_arg(c, word) // Add `word` as an argument to command `c`. This increments `c->argc` // and augments `c->argv`. static void command_append_arg(command* c, char* word) { c->argv = (char**) realloc(c->argv, sizeof(char*) * (c->argc + 2)); c->argv[c->argc] = word; c->argv[c->argc + 1] = NULL; ++c->argc; } // handle_redirection // does the operation of rediredtion (<, >, or 2>) void handle_redirection (command* c, pid_t pgid){ (void) pgid; if(c->file_in){ if(opendir(dirname(c->file_in_name)) == 0) { printf("No such file or directory\n"); exit(1); } if (stat_file(c->file_in_name)) { int file_in = open(c->file_in_name, O_CREAT | O_RDONLY, 0664); dup2 (file_in, STDIN_FILENO); close (file_in); } else { printf("No such file or directory\n"); exit(1); } } if(c->file_out){ if(opendir(dirname(c->file_out_name)) == 0) { printf("No such file or directory\n"); exit(1); } int file_out = open(c->file_out_name, O_CREAT | O_WRONLY | O_TRUNC, 0664); dup2 (file_out, STDOUT_FILENO); close (file_out); } if(c->file2_out) { if(opendir(dirname(c->file2_out_name)) == 0) { printf("No such file or directory\n"); exit(1); } int file2_out = open(c->file2_out_name, O_CREAT | O_WRONLY | O_TRUNC, 0664); dup2 (file2_out, STDERR_FILENO); close (file2_out); } } // COMMAND EVALUATION // start_command(c, pgid) // Start the single command indicated by `c`. Sets `c->pid` to the child // process running the command, and returns `c->pid`. // // PART 1: Fork a child process and run the command using `execvp`. // PART 5: Set up a pipeline if appropriate. This may require creating a // new pipe (`pipe` system call), and/or replacing the child process's // standard input/output with parts of the pipe (`dup2` and `close`). // Draw pictures! // PART 7: Handle redirections. // PART 8: The child process should be in the process group `pgid`, or // its own process group (if `pgid == 0`). To avoid race conditions, // this will require TWO calls to `setpgid`. pid_t start_command(command* c, pid_t pgid) { pid_t fork_rv; if (c->pipe_sender) { if (pipe(pipefd[pipe_fd_counter]) != 0) perror("failed to create pipe\n"); pipe_fd_counter++; } if (c->pipe_receiver && !c->pipe_sender) { end_of_pipe = 1; } fork_rv = fork(); c->pgid = pgid; if (fork_rv == -1) { perror("Could not fork!\n"); } switch (fork_rv){ case 0: //child process setpgid(c->pgid, c->pgid); if (c->pipe_sender && !c->pipe_receiver) { dup2(pipefd[0][1], 1); close(pipefd[0][0]); close(pipefd[0][1]); } if (c->pipe_receiver && c->pipe_sender) { dup2(pipefd[pipe_fd_counter -2][0], 0); dup2(pipefd[pipe_fd_counter -1][1], 1); for (int i = 0; i < pipe_fd_counter; i++) { close(pipefd[i][0]); close(pipefd[i][1]); } } if (c->pipe_receiver && !c->pipe_sender){ dup2(pipefd[pipe_fd_counter -1][0], 0); for (int i = 0; i < pipe_fd_counter; i++) { close(pipefd[i][0]); close(pipefd[i][1]); } } handle_redirection (c, pgid); if (execvp(c->argv[0], c->argv) == -1) { printf("Couldn't execute the program: %s\n", strerror(errno)); _exit(0); } else { //child running process successfully } break; default: //parent process setpgid(c->pgid, c->pgid); if (c->pipe_sender) { //not encountered } else if (c->pipe_receiver) { //not encountered } c->pid = fork_rv; return c->pid; break; } c->pid = fork_rv; return c->pid; } // run_conditional_list // executes commands denoted as having the attribute (data member) // logical_and_condition or logical_or_condition void run_conditional_list(struct commands* column) { int background = 0; //boolean for run in background (1) or not (0) if (column->pgid == background_pgid) { background = 1; } else { background = 0; } int truth_status = column->truth_status; //boolean for current state of && and || evaluations int need_run_logical = 1; //boolean for whether next logical need run int exit_status; //exit status of child process pid_t child_pid = -1; //child pid initialized at -1 struct command *argp = column->command_head; if (argp->argc == 0){ if (argp->logical_and_condition == 1 && truth_status == 0) { need_run_logical = 0; } if (argp->logical_or_condition == 1 && truth_status == 1) { need_run_logical = 0; } argp = argp->next; } while (argp != NULL && !SIGINT_RECEIVED) { // process cd commands in parent if (strcmp(argp->argv[0], "cd") == 0) { truth_status = 1; if(opendir(argp->argv[1]) == 0) { truth_status = 0; } if (chdir (argp->argv[1]) != 0) { truth_status = 0; } if(argp->file_in){ if(opendir(dirname(argp->file_in_name)) == 0) { printf("No such file or directory\n"); truth_status = 0; } if (stat_file(argp->file_in_name)) { int file_in = open(argp->file_in_name, O_CREAT | O_RDONLY, 0664); dup2 (file_in, STDIN_FILENO); close (file_in); } else { printf("No such file or directory\n"); truth_status = 0; } } if(argp->file_out) { if(opendir(dirname(argp->file_out_name)) == 0) { printf("No such file or directory\n"); truth_status = 0; } int file_out = open(argp->file_out_name, O_CREAT | O_WRONLY | O_TRUNC, 0664); dup2 (file_out, STDOUT_FILENO); close (file_out); } if(argp->file2_out) { if(opendir(dirname(argp->file2_out_name)) == 0) { printf("No such file or directory\n"); truth_status = 0; } int file2_out = open(argp->file2_out_name, O_CREAT | O_WRONLY | O_TRUNC, 0664); dup2 (file2_out, STDERR_FILENO); close (file2_out); } need_run_logical = 1; if (argp->logical_and_condition == 1) { if (truth_status == 0) { need_run_logical = 0; } } if (argp->logical_or_condition == 1) { if (truth_status == 1){ need_run_logical = 0; } } argp = argp->next; continue; } if (need_run_logical) { waitpid(-1, 0, WNOHANG); child_pid = start_command(argp, column->pgid); waitpid(argp->pid, &exit_status, 0); if (WEXITSTATUS(exit_status) == 0) { truth_status = 1; } else { truth_status = 0; } } if (!argp->pipe_sender && !background) { if (WIFEXITED(exit_status)) { if (WIFSIGNALED(exit_status) != 0 && WTERMSIG(exit_status) == SIGINT) { kill(argp->pgid, SIGINT); set_foreground(0); _exit(0); } if (WEXITSTATUS(exit_status) == 0) { truth_status = 1; } else { truth_status = 0; } } } need_run_logical = 1; if (argp->logical_and_condition == 1) { if (truth_status == 0){ need_run_logical = 0; } } if (argp->logical_or_condition == 1) { if (truth_status == 1){ need_run_logical = 0; } } argp = argp->next; } if (background) { while (child_pid != waitpid(child_pid, &exit_status, WNOHANG)) {} set_foreground(0); _exit(0); } column->truth_status = truth_status; } // run_list() // Run the command list starting at `c`. // // PART 1: Start the single command `c` with `start_command`, // and wait for it to finish using `waitpid`. // The remaining parts may require that you change `struct command` // (e.g., to track whether a command is in the background) // and write code in run_list (or in helper functions!). // PART 2: Treat background commands differently. // PART 3: Introduce a loop to run all commands in the list. // PART 4: Change the loop to handle conditionals. // PART 5: Change the loop to handle pipelines. Start all processes in // the pipeline in parallel. The status of a pipeline is the status of // its LAST command. // PART 8: - Choose a process group for each pipeline. // - Call `set_foreground(pgid)` before waiting for the pipeline. // - Call `set_foreground(0)` once the pipeline is complete. // - Cancel the list when you detect interruption. void run_list(struct commands* column) { int background = column->background; //boolean for run in background (1) or not (0) int truth_status = 1; //boolean for current state of && and || evaluations pid_t fork_rv; //child's pid (on successful fork) int exit_status; //exit status of child process pid_t child_pid = -1; struct command *argp = column->command_head; if (background) { setpgid(background_pgid, background_pgid); if ((fork_rv = fork()) < 0){ perror("shell fork failed to execute"); _exit(1); } else if (fork_rv > 0) { if (column->commands_count == 1 && !column->pipe_sender && !column->pipe_receiver) sleep(1); //T29 grade serv. oddity waitpid(-1, 0 , WNOHANG); return; } column->pgid = background_pgid; } else { setpgid(foreground_pgid, foreground_pgid); column->pgid = foreground_pgid; } if ((argp->logical_and_condition || argp->logical_or_condition) && (column->pipe_sender == 0)) { run_conditional_list(column); if (background) { waitpid(-1, 0, WNOHANG); _exit(0); } return; } if ((argp->logical_and_condition || argp->logical_or_condition) && (column->pipe_sender == 1)) { truth_status = column->truth_status; if (argp->argc == 0) { if (argp->logical_and_condition == 1 && truth_status == 0) { return; } if (argp->logical_or_condition == 1 && truth_status == 1) { return; } argp = argp->next; } if (background) { _exit(0); waitpid(-1, 0, WNOHANG); } } while (argp != NULL && !SIGINT_RECEIVED) { //cd must be handled directly within parent if (strcmp(argp->argv[0] , "cd") == 0){ truth_status = 1; if(opendir(argp->argv[1]) == 0) { truth_status = 0; } if (chdir (argp->argv[1]) != 0) { truth_status = 0; } handle_redirection(argp, argp->pgid); argp = argp->next; continue; } waitpid(-1, 0, WNOHANG); child_pid = start_command(argp, column->pgid); if (argp->pipe_receiver && !argp->pipe_sender) { for (int i = 0; i < pipe_fd_counter; i++){ close(pipefd[i][0]); close(pipefd[i][1]); } if(end_of_pipe){ end_of_pipe = 0; pipe_fd_counter = 0; } } if (!argp->pipe_sender ) { if (background) { waitpid(argp->pid, &exit_status, WNOHANG); } else { waitpid(argp->pid, &exit_status, 0); } if (WIFEXITED(exit_status)) { if (WIFSIGNALED(exit_status) != 0 && (WTERMSIG(exit_status) == SIGINT)) { kill(argp->pgid, SIGINT); set_foreground(0); _exit(0); } if (WEXITSTATUS(exit_status) == 0) { truth_status = 1; } else { truth_status = 0; } } } argp = argp->next; } if (background) { while (child_pid != waitpid(child_pid, &exit_status, WNOHANG)){} _exit(0); set_foreground(0); } column->truth_status = truth_status; } // eval_line(c) // Parse the command list in `s` and run it via `run_list`. void eval_line(const char* s) { int type = 0; //the type of the current token char* token = NULL; //the current token itself // build the command int make_new_command = 0; //boolean for add to column int make_new_commands = 0; //boolean for add to row int pipe_receiver_next = 0; //boolean for whether next command is a pipe_reader command* c = command_alloc(); //create a place for a command create_commands(c); //create a place for a list of commands while ((s = parse_shell_token(s, &type, &token)) != NULL && !SIGINT_RECEIVED) { if (make_new_command == 1) { c = command_alloc(); if (pipe_receiver_next) {c->pipe_receiver = 1; pipe_receiver_next = 0;} if (make_new_commands == 0) { add_command(c); } else { add_commands(c); make_new_commands = 0; } make_new_command = 0; } c->type = type; switch (type) { case TOKEN_NORMAL: if (strcmp((const char *)token , "n") == 0) { if (c->argc > 0) { make_new_command = 1; make_new_commands = 1; } } else command_append_arg(c, token); break; case TOKEN_REDIRECTION: switch (token[0]) { case '<': c->file_in = 1; s = parse_shell_token(s, &type, &token); c->file_in_name = token; break; case '>': c->file_out = 1; s = parse_shell_token(s, &type, &token); c->file_out_name = token; break; case '2': c->file2_out = 1; s = parse_shell_token(s, &type, &token); c->file2_out_name = token; break; default : perror("tokenizer is broken\n"); } break; case TOKEN_SEQUENCE: make_new_command = 1; make_new_commands = 1; break; case TOKEN_BACKGROUND: c->background = 1; commands_ending->background = c->background; make_new_command = 1; make_new_commands = 1; break; case TOKEN_PIPE: c->pipe_sender = 1; commands_ending->pipe_sender = c->pipe_sender; make_new_command = 1; pipe_receiver_next = 1; break; case TOKEN_AND: if (c->pipe_receiver == 1){ c = command_alloc(); add_commands(c); } c->logical_and_condition = 1; make_new_command = 1; break; case TOKEN_OR: if (c->pipe_receiver == 1) { c = command_alloc(); add_commands(c); } c->logical_or_condition = 1; make_new_command = 1; break; case TOKEN_LPAREN: make_new_command = 1; make_new_commands = 1; break; case TOKEN_RPAREN: make_new_command = 1; make_new_commands = 1; break; default: break; } } // execute it int truth_status = 1; struct commands *argp = commands_beginning; while (argp != NULL && !SIGINT_RECEIVED) { run_list(argp); truth_status = argp->truth_status; argp = argp->next; if (argp) argp->truth_status = truth_status; } free_commands(); } //interruption_signal_handler // signal handler function for SIGNINT void interruption_signal_handler (int interruption){ (void) interruption; SIGINT_RECEIVED = 1; } int main(int argc, char* argv[]) { FILE* command_file = stdin; int quiet = 0; shell_pgid = getpid(); //this is the pid of the shell itself setpgid(shell_pgid, shell_pgid); // Check for '-q' option: be quiet (print no prompts) if (argc > 1 && strcmp(argv[1], "-q") == 0) { quiet = 1; --argc, ++argv; } // Check for filename option: read commands from file if (argc > 1) { command_file = fopen(argv[1], "rb"); if (!command_file) { perror(argv[1]); exit(1); } } // - Put the shell into the foreground // - Ignore the SIGTTOU signal, which is sent when the shell is put back // into the foreground set_foreground(0); handle_signal(SIGTTOU, SIG_IGN); handle_signal(SIGINT, interruption_signal_handler); char buf[BUFSIZ]; int bufpos = 0; int needprompt = 1; while (!feof(command_file)) { // Print the prompt at the beginning of the line if (needprompt && !quiet) { printf("\nsh61[%d]$ ", getpid()); fflush(stdout); needprompt = 0; } // Read a string, checking for error or EOF if (fgets(&buf[bufpos], BUFSIZ - bufpos, command_file) == NULL) { if (ferror(command_file) && errno == EINTR) { // ignore EINTR errors clearerr(command_file); buf[bufpos] = 0; } else { if (ferror(command_file)) perror("sh61"); break; } } // If a complete command line has been provided, run it bufpos = strlen(buf); if ((bufpos == BUFSIZ - 1 || (bufpos > 1 && buf[bufpos - 1] == '\n'))) { if (strcmp(buf, "exit\n") == 0 || strcmp(buf, "exit\r\n") == 0 || strcmp(buf, "exit") == 0) return 0; eval_line(buf); } bufpos = 0; needprompt = 1; // Handle zombie processes and/or interrupt requests // Reap all zombie processes waitpid(-1, 0, WNOHANG); SIGINT_RECEIVED = 0; } return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<assert.h> struct node { int data; struct node* next; }; int Length(struct node* head) { int count = 0; struct node* current = head; while (current != NULL) { count++; current=current->next; } return(count); } // Given a reference (pointer to pointer) to the head // of a list and an int, push a new node on the front of the list. // Creates a new node with the int, links the list off the .next of the // new node, and finally changes the head to point to the new node. void Push(struct node** headRef, int newData) { struct node* newNode = (struct node*) malloc(sizeof(struct node)); // allocate node newNode->data = newData;// put in the data newNode->next = (*headRef);// link the old list off the new node (*headRef) = newNode;// move the head to point to the new node } // Build and return the list {1, 2, 3} struct node* BuildOneTwoThree() { struct node* head = NULL;// Start with the empty list Push(&head, 3);// Use Push() to add all the data Push(&head, 2); Push(&head, 1); return(head); } // Visualize Linked List void Visualize(struct node* head) { struct node* current = head; while (current != NULL) { printf("%d-->", current->data); current=current->next; } printf("NULL\n"); } //1 - Count() //Builds a list and counts the number of times a given int occurs int Count(struct node* head, int search) { int count = 0; struct node* current = head; while(current != NULL) { if (current->data == search) { count++; } current = current->next; } return count; } void CountTest() { struct node* list; list = BuildOneTwoThree(); int count = Count(list, 2); assert(count == 1); } //2 -GetNth() //Write a GetNth() function that takes a linked list and an integer index and //returns the data value stored in the node at that index position. int GetNth(struct node* head, int index) { assert(index < Length(head)); struct node* current = head; while(current != NULL && index-- != 0) { current = current->next; } return current->data; } void GetNthTest() { struct node* myList = BuildOneTwoThree(); int lastNode = GetNth(myList, 2); assert(lastNode == 3); } //3 - DeleteList() //Write a func that takes a list, deallocates all of its memory and sets its head //pointer to NULL void DeleteList(struct node** headRef) { struct node* current = *headRef; struct node* next; while(current != NULL) { next = current->next; free(current); current = next; } *headRef = NULL; } void DeleteListTest() { struct node* myList = BuildOneTwoThree(); DeleteList(&myList); assert(myList == NULL); } //4 - Pop() //function is inverse of pop. pop takes a non empty list, deletes the head node, //and returns the head node's data. int Pop(struct node** headRef) { assert(Length(*headRef) > 0); struct node* current = *headRef; assert(current != NULL); int value = current->data; *headRef = current->next; free(current); return value; } void PopTest() { struct node* head = BuildOneTwoThree();// build {1, 2, 3} int a = Pop(&head);// deletes "1" node and returns 1 assert(a==1); int b = Pop(&head);// deletes "2" node and returns 2 assert(b==2); int c = Pop(&head);// deletes "3" node and returns 3 assert(c==3); int len = Length(head);// the list is now empty, so len == 0 assert(len == 0); DeleteList(&head); } //5 - InserNth() //insert a new node at any index within a list. Push() is similar, //but can only insert a node at the head of a list. void InsertNth(struct node** headRef, int index, int value) { assert(index < Length(*headRef) + 1); struct node* curr = *headRef; int i = 0; while (++i < index) { curr = curr->next; } struct node* newNode = (struct node*) malloc(sizeof(struct node)); newNode->data = value; if (curr == NULL) { *headRef = newNode; } else { newNode->next = curr->next; curr->next = newNode; } } void InsertNthTest() { struct node* head = NULL; printf("Running InsertNthTest\n"); Visualize(head); InsertNth(&head, 0, 13); Visualize(head); InsertNth(&head, 1, 42); Visualize(head); InsertNth(&head, 1, 5); assert(Length(head) == 3); Visualize(head); DeleteList(&head); } //6 - SortedInsert() //Write a func which given a list that is sorted in increasing order. void SortedInsert(struct node** headRef, struct node* newNode) { printf("Inserting Node with data %d\n", newNode->data); struct node* current = *headRef; struct node* next = NULL; if (current == NULL) { //Handle case of list being empty newNode->next = *headRef; *headRef = newNode; return; } while (current != NULL) { next = current->next; if (current->data > newNode->data) { newNode->next = current; current->next = next; if (current == *headRef) { *headRef = newNode; } return; } if (next == NULL) { current->next = newNode; newNode->next = next; } else if (newNode->data <= next->data) { current->next = newNode; newNode->next = next; return; } current = current->next; } } void SortedInsertTest() { printf("Running SortedInsertTest\n"); struct node* head = NULL;// Start with the empty list Push(&head, 10);// Use Push() to add all the data Push(&head, 5); Push(&head, 3);// Use Push() to add all the data Push(&head, 2); Push(&head, 1); Visualize(head); struct node* zero = (struct node*) malloc(sizeof(struct node)); zero->data = 0; SortedInsert(&head, zero); Visualize(head); struct node* four = (struct node*) malloc(sizeof(struct node)); four->data = 4; SortedInsert(&head, four); Visualize(head); struct node* eight = (struct node*) malloc(sizeof(struct node)); eight->data = 8; SortedInsert(&head, eight); Visualize(head); struct node* eighty = (struct node*) malloc(sizeof(struct node)); eighty->data = 80; SortedInsert(&head, eighty); Visualize(head); printf("Test empty SortedInsertTest\n"); struct node* empty = NULL; Visualize(empty); struct node* first = (struct node*) malloc(sizeof(struct node)); first->data = 10; SortedInsert(&empty, first); Visualize(empty); printf("Try adding something else"); struct node* two = (struct node*) malloc(sizeof(struct node)); two->data = -2; SortedInsert(&empty, two); Visualize(empty); DeleteList(&empty); DeleteList(&head); } //7 - InsertSort Test //Write an InsertSort function which given a list, rearranges its nodes so they are sorted //in increasing order. It should use SortedInsert(); void InsertSort(struct node** headRef) { struct node* newHead = NULL; struct node* current = *headRef; struct node* next; while (current != NULL) { next = current->next; SortedInsert(&newHead, current); current = next; } *headRef = newHead; } void InsertSortTest() { printf("==========\nStarting Insert Sort Test\n"); struct node* head = NULL; //Push non ordered nodes Push(&head, 10); Push(&head, 12); Push(&head, 48); Push(&head, 8); Push(&head, -2); Push(&head, 3); Visualize(head); InsertSort(&head); Visualize(head); DeleteList(&head); } //8 - Append Test //Write a func that takes two lists a and b and appends b onto the end of a void Append(struct node** aRef, struct node** bRef) { printf("Appending list A (length: %d) list B (length: %d)\n", Length(*aRef), Length(*bRef)); struct node* itr = *aRef; if (*aRef == NULL) { *aRef = *bRef; } else if (*bRef != NULL) { while (itr->next != NULL) { itr = itr->next; } itr->next = *bRef; } *bRef = NULL; } void AppendTest() { printf("============================\nAppend Tests\n"); struct node* a = NULL; struct node* b = NULL; struct node* c = NULL; struct node* d = NULL; struct node* e = NULL; struct node* f = NULL; struct node* g = NULL; struct node* h = NULL; printf("Testing a,b as normal populated lists\n"); Push(&a, 2); Push(&a, 13); Push(&a, 581); Push(&b, 132); Push(&b, 1); Push(&b, 783); Visualize(a); Visualize(b); Append(&a, &b); Visualize(a); Visualize(b); printf("Testing a,b as empty lists\n"); printf("A empty Not B\n"); d = BuildOneTwoThree(); Visualize(c); Visualize(d); Append(&c,&d); Visualize(c); Visualize(d); printf("B empty Not A\n"); e = BuildOneTwoThree(); Visualize(e); Visualize(f); Append(&e,&f); Visualize(e); Visualize(f); printf("A empty B empty\n"); Visualize(g); Visualize(h); Append(&g,&h); Visualize(g); Visualize(h); //Delete //DeleteList(&a); //DeleteList(&b); //DeleteList(&c); //DeleteList(&d); //DeleteList(&e); //DeleteList(&f); //DeleteList(&g); //DeleteList(&h); } int main() { CountTest(); GetNthTest(); DeleteListTest(); PopTest(); InsertNthTest(); SortedInsertTest(); InsertSortTest(); AppendTest(); return 0; }
C
#include "sort.h" /** * shell_sort - sorts an array using the Shell sort algorithm * using the Knuth sequence * @array: the array * @size: the size of the array * * Return: Nothing */ void shell_sort(int *array, size_t size) { size_t interval = 1; size_t outer, inner; int valueToInsert; if (array != NULL && size > 1) { /* Calculate interval*/ while (interval < (size / 3)) interval = interval * 3 + 1; while (interval > 0) { for (outer = interval; outer < size; outer++) { /*Select value to be inserted*/ valueToInsert = array[outer]; inner = outer; /*shift element towards right*/ while (inner > interval - 1 && array[inner - interval] >= valueToInsert) { array[inner] = array[inner - interval]; inner = inner - interval; } array[inner] = valueToInsert; } /*calculate interval*/ interval = (interval - 1) / 3; print_array(array, size); } } }
C
#include <stdio.h> int main() { int a = 0, b = 0, rs = 0, cont; scanf("%d %d", &a, &b); if(a >= b) { for(cont = a - 1; cont > b; cont--) { if((cont % 2) != 0) rs += cont; } } else { for(cont = a + 1; cont < b; cont++) { if((cont % 2) != 0) rs += cont; } } printf("%d\n", rs); return 0; }
C
#ifndef __LIBAEDS_DATA_CONTAINER_LINKEDLIST_H__ #define __LIBAEDS_DATA_CONTAINER_LINKEDLIST_H__ #include <stdbool.h> #include <stddef.h> #include <libaeds/data/container/iterator.h> #include <libaeds/memory/allocator.h> // A LinkedNode is a node of a linked list. typedef struct LinkedNode LinkedNode; // A linked list is a list that uses linked nodes as storage. typedef struct LinkedList LinkedList; extern const size_t sizeof_lnode; // Returns the data pointer contained in the node. // Complexity: O(1) void* lnode_data(const LinkedNode*); // The data referenced by a LinkedNode is the contained pointer casted to the original type. #define lnode_tdata(node, type) ((type*) lnode_data(node)) // Creates a linked list that will use the specified allocator once to allocate the // LinkedList struct, and the node_allocator for each node allocation. // The list only allocates nodes one at a time. Therefore, it supports any node_allocator // that provides `al_alloc(allocator, 1, sizeof_lnode)` and the correspondent al_dealloc. // Complexity: O(1) LinkedList* new_llist(const Allocator* allocator, const Allocator* node_allocator); // Delete a linked list, deallocating the memory used by the list and nodes via the // allocators specified in new_llist. // The delete function is called with the supplyed allocator for each contained element, // unless NULL is supplyed as the delete function. // Complexity: O(n) where n is the number of elements in the list. void delete_llist(LinkedList**, void (*delete)(const Allocator*, void*), const Allocator*); // Returns the number of elements in the list. // Complexity: O(1) size_t llist_size(const LinkedList*); // Returns wether a linked list contains no elements or not. // Complexity: O(1) bool llist_empty(const LinkedList*); // Pushes an element to the head of a linked list. // Complexity: O(1) void llist_push_head(LinkedList*, const void*); // Pushes an element to the tail of a linked list. // Complexity: O(1) void llist_push_tail(LinkedList*, const void*); // Pops an element from the head of a linked list. // Returns NULL if the operation fails. // This operation fails if the linked list is empty. // Complexity: O(1) void* llist_pop_head(LinkedList*); // Pop from the head. // Returns an iterator to the first element of the list. // Complexity: O(1) Iterator llist_begin(const LinkedList*); #endif /* __LIBAEDS_DATA_CONTAINER_LINKEDLIST_H__ */
C
#include <stdio.h> #include <stdlib.h> #include "lista.h" int main(int argc, char *argv[]) { Lista l; Celula * p; iniciarLista(&l); inserirInicio(&l, 1); inserirInicio(&l, 0); inserirInicio(&l, 3); inserirInicio(&l, 4); inserirInicio(&l, 5); imprimir(&l); countElementos(&l); p = busca(&l, 3); inserirProximo(&l, p, 8); inserirProximo(&l, p, 100); imprimir(&l); countElementos(&l); p = busca(&l, 8); countAntes(&l, p); p = busca(&l, 8); countDepois(&l, p); return 0; }
C
// fibonacci sequence int main(){ // test number int n = 6; int fib[n+2]; // beginning of fibonacci sequence fib[0] = 0; fib[1] = 1; // perform sequence and populate array for (int i = 2; i <= n; i++){ fib[i] = fib[i-1] + fib[i-2]; } // the n-th number in the sequence int result = fib[n]; printf("The %dth number is %d\n", n, result); }
C
#include <stdbool.h> #include "keyboard.h" #include "print.h" #include "types.h" #include "chars.h" #include "utils.h" #include "color_spin.h" static ui8 get_input_keycode() { ui8 code = 0; while (!code) { nanosleep(10000); show_date_time(); show_color_spin(); show_random_ship(); code = inb(KEYBOARD_PORT); } // This outputs key code at the bottom of the screen for debug pprint_str(66, 23, "Keycode:", PRINT_COLOR_YELLOW, PRINT_COLOR_BLACK); pprint_int_pad(75, 23, code, 4, PRINT_COLOR_YELLOW, PRINT_COLOR_BLACK); return code; } // Returns true if pressed Enter, or false if pressed Esc bool input_str(char* str, int max_len) { bool capslock = false; bool shift = false; bool alt = false; bool ctrl = false; bool numlock = true; bool scrolllock = false; ui32 repeats = 0; ui8 last_keycode = 0; int pos = 0; while (true) { ui8 c = get_input_keycode(); // Skip repeating keys if (c == last_keycode) { ++repeats; if (repeats < 40 || repeats % 8 != 0) { continue; } } else { repeats = 0; } last_keycode = c; if (c == KEY_LEFT_SHIFT_RELEASE) { shift = false; } if (c == KEY_RIGHT_SHIFT_RELEASE) { shift = false; } // Skip depressing other keys if (c > 127) { continue; } if (c == KEY_ENTER) { str[pos] = '\0'; return true; } else if (c == KEY_ESC) { str[pos] = '\0'; return false; } else if (c == KEY_BACKSPACE) { if (pos) { pos--; clear_col(); } } else if (c == KEY_LEFT_SHIFT_PRESS) { shift = true; } else if (c == KEY_CAPS_LOCK_PRESS) { capslock = !capslock; } else if ((c >=2 && c <= 13) || (c >= 16 && c <= 27) || (c >= 30 && c <= 41) || (c >= 43 && c <= 53) || c == 57) { if (pos + 1 < max_len) { char ch; if (capslock || shift) { ch = get_ascii_char(c); } else { ch = get_ascii_char_lower(c); } str[pos] = ch; print_char(ch); pos++; } } } }
C
#include<stdio.h> #include<stdlib.h> typedef enum boolean {FALSE,TRUE} Boolean; /*Pre: Points to the message to be printed Post: the function prints the message and terminates the program.*/ void Error(const char* s) { fprintf(stderr,"%s\n",s); exit(1); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "gasdev.c" typedef double(*funcPtr)(double, double, int*); typedef struct distributor{ funcPtr func; char* name; double arg1; double arg2; } distributor; double uniform_random(double l, double r, int* idum); double gaussian_random(double m, double s, int* idum); void make_distribution(distributor generator, int sections, int samples); int main(){ distributor distributors[2] = { { uniform_random, "Uniform Distribution", -3.0, 2.0 }, { gaussian_random, "Gaussian Distribution", -0.5, 1.5 } }; for(int samples = 100; samples<=1000000; samples*=100){ for(int sections=50; sections<=100; sections*=2){ for(int i=0;i<2;i++){ make_distribution(distributors[i], sections, samples); } } } return 0; } double uniform_random(double l, double r, int* idum){ double p = ran1(idum); return l + (r-l)*p; } double gaussian_random(double m, double s, int* idum){ double n = gasdev(idum); return n*s + m; } void make_distribution(distributor generator, int sections, int samples){ char* name = generator.name; funcPtr func = generator.func; double arg1 = generator.arg1; double arg2 = generator.arg2; double l,r; double interval; int idum=1; // set interval boundary if(name=="Uniform Distribution"){ l=arg1; r=arg2; } else{ l=arg1-4*arg2; r=arg1+4*arg2; } interval = (r-l)/sections; // make distribution int cnt[201] = { 0 }; for(int i=0;i<samples;i++){ double num; do{ num = func(arg1, arg2, &idum); }while(num<l || num>=r); int step = (int)((num-l)/interval); cnt[step]++; } // save distribution char filename[50]; sprintf(filename, "distributions/%s_%d_%d.csv", name,samples,sections); printf("%s\n\n", filename); FILE* fp; fp=fopen(filename, "w+"); fprintf(fp,"x,cnt\n"); for(int i=0;i<sections;i++){ fprintf(fp,"%lf,%d\n",l+(i+1/2)*interval,cnt[i]); } fclose(fp); }
C
/* * control.c * Author: Christian Würthner * Description: control for project 2 */ #include "control.h" int main(int argc, char **argv) { /* Check argument count */ if(argc < 5) { console_error("CONTROL", "Not enough arguments, usage: " "mem‐sim pages quantum pr‐policy trace‐file [verbose [step]]"); return ERR_NO_TOO_FEW_ARGS; } /* Parse all args */ memory_frame_count = atoi(argv[1]); scheduler_rr_quantum = atoi(argv[2]); char *trace_file_name = argv[4]; /* Using strcmp to create a unique value for the page replacement algo */ switch(strcmp("fifo", argv[3])) { case 0: pager_page_replacement_algo = 0; break; case -6: pager_page_replacement_algo = -6; break; case 52: pager_page_replacement_algo = 52; break; default: console_error("CONTROL", "%s is not a valid page replacement algorithm", argv[3]); return ERR_NO_UNDEFINED_PAGE_REPLACEMENT_ALGORITHM; } /* If the 6. parameter is verbose, set verbose mode to true */ if(argc > 5 && strcmp(argv[5], "verbose") == 0) { console_verbose_mode = true; console_log("CONTORL", "Verbose mode is enabled"); } /* If the 7. parameter is step, enable step mode */ if(argc > 6 && strcmp(argv[6], "step") == 0) { control_step_mode = true; console_log("CONTORL", "Step mode is enabled"); } /* Set traps for cpu */ memory_page_fault = &scheduler_trap_page_fault; cpu_context_switch = &scheduler_trap_context_switch; cpu_timer_done = &scheduler_trap_context_switch; /* Read process trace */ control_create_process_arrival_queue(trace_file_name); print_list(process_queue_head, "arrival_list"); /* Prepare memory */ memory_init(); uint64_t skip_step_beaks = 0; /* Perform ticks [MAIN LOOP] */ while(process_queue_head != NULL || !scheduler_all_processes_done()) { console_log("CONTROL", "================================================================" "==============="); console_log("CONTROL", "CPU time: %" PRIu64, cpu_time); /* Check if a new process arrives to the current time */ if(process_queue_head != NULL && process_queue_head->start_time == cpu_time) { /* Add it and remove it from the arrival queue */ pcb_t *p = process_queue_head; process_queue_head = p->next; control_load_memory_trace(p, ""); scheduler_add_process(p); } /* Perform a pager tick */ pager_tick(); /* Perform a scheduler tick, if the tick is not used perform a cpu tick, otherwise inform the cpu about the wasted tick */ if(scheduler_tick()) { cpu_tick(); } else { cpu_stall_tick(); } /* Increase CPU time */ cpu_time++; /* If step mode is enabled wait for confirm of user */ if(control_step_mode && skip_step_beaks == 0) { /* Prompt */ console_log_force("CONTROL", "Press ENTER to continue or type a " "number to skip more than one step"); /* Read line */ char input[64]; uint8_t input_length = 0; /* While not enter is pressed */ while((input[input_length++] = fgetc(stdin)) != '\n') {} /* Terminate string */ input[input_length-1] = 0; /* If a number was typed, parse number and skip next steps */ if(input_length > 0) { skip_step_beaks = atoi(input); } } /* Decrement skip_step_beaks */ if(skip_step_beaks > 0) { skip_step_beaks--; } } /* Print results */ console_log("RESULT", "================================================================" "==============="); console_log_force("RESULT", "%-20s %" PRIu64, "Total CPU time:", cpu_time-1); console_log_force("RESULT", "%-20s %" PRIu64, "Total page faults:", memory_page_faults); console_log_force("RESULT", "%-20s %" PRIu64, "Total cpu idle time:", cpu_stall_counter); } /* Loads the process file and puts the proceeses into process_queue_head */ void control_create_process_arrival_queue(char *trace_file_name) { /* Open file, handle errors */ FILE* trace_file; if((trace_file = fopen(trace_file_name, "r")) == NULL) { console_error("CONTROL", "ERROR: Unable to read process trace file \"%s\" (%s)", trace_file_name, strerror(errno)); exit(ERR_NO_UNABLE_OPEN_PROCESS_TRACE); } /* Iterate over all lines */ char line[1024]; int32_t line_result = 0; uint32_t pid_counter = 0; for(;;) { /* Read current line */ line_result = read_line(trace_file, line); /* If the line is empty, we are at the end of the file, break */ if(line_result == 0) { break; } /* If a negative value is returned, a error occured */ if(line_result < 0) { console_error("CONTROL", "ERROR: Unable to read memory trace file \"%s\" (%s)", trace_file_name, strerror(errno)); exit(ERR_NO_UNABLE_OPEN_MEMORY_TRACE); } /* Split the line at tab to get the single values */ char values[4][512]; char *p; for(uint8_t i=0; i<4; i++) { /* Get part */ p = strtok(i==0 ? line : NULL, "\t "); /* Handle error */ if(p == NULL) { console_error("CONTROL", "ERROR: error while parsing trace file! (%s)", strerror(errno)); exit(ERR_NO_PROCESS_TRACE_PARSE); } /* copy */ int length = strlen(p); memcpy(values+i, p, length); values[i][length] = 0; } /* Create new pcb and fill in information */ pcb_t *pcb = malloc(sizeof(pcb_t)); pcb->name = malloc(strlen(values[0])); pcb->pid = pid_counter++; memcpy(pcb->name, values, strlen(values[0])+1); pcb->cpu_time = 0; pcb->start_time = SECS_TO_TICKS(atof(values[1])); pcb->waiting_time = 0; pcb->io_count = atof(values[3]); pcb->page_faults = 0; pcb->end_time = -1; pcb->instruction_pointer = NULL; pcb->next = NULL; /* Print result */ console_log("CONTROL", "SUCESS: created process control block for \"%s\"", pcb->name); console_log("CONTROL", "\tstart_time = %" PRIu64, pcb->start_time); console_log("CONTROL", "\tcpu_time = %" PRIu64, pcb->cpu_time); console_log("CONTROL", "\tio_count = %" PRIu64, pcb->io_count); /* Link pcb to previous in queue or set as head if queue is empty */ if(process_queue_head == NULL) { process_queue_head = pcb; } else { process_queue_tail->next = pcb; } /* Set pcb as new tail in queue */ process_queue_tail = pcb; } } /* Loads the memory trace file for the given process from the given directory */ void control_load_memory_trace(pcb_t *process, char *dir) { /* Define needed variables */ char line[1024]; int32_t line_result = 0; instruction_t *last = NULL; /* Generate the full path */ char full_path[PATH_MAX]; sprintf(full_path, "%s%s.mem", dir, process->name); /* Open file */ FILE* trace_file; if((trace_file = fopen(full_path, "r")) == NULL) { console_error("CONTROL", "ERROR: Unable to read memory trace file \"%s\" (%s)", full_path, strerror(errno)); exit(ERR_NO_UNABLE_OPEN_MEMORY_TRACE); } /* Iterate over all lines */ for(;;) { /* Read current line */ line_result = read_line(trace_file, line); /* If the line is empty, we are at the end of the file, break */ if(line_result == 0) { break; } /* If a negative value is returned, a error occured */ if(line_result < 0) { console_error("CONTROL", "ERROR: Unable to read memory trace file \"%s\" (%s)", full_path, strerror(errno)); exit(ERR_NO_UNABLE_OPEN_MEMORY_TRACE); } /* Read number and append to memory_trace list */ instruction_t *t = malloc(sizeof(instruction_t)); t->address = atof(line); /* Append to list or staet list */ if(process->instruction_pointer == NULL) { process->instruction_pointer = t; } else { last->next = t; } /* Set t to last */ last = t; last->next = NULL; } } /* Reads a single line from the file pointer */ int32_t read_line(FILE *file, char *dest) { uint32_t line_position = 0; size_t read_count = 0; for(;;) { /* Read single byte */ read_count = fread(dest+line_position, 1, 1, file); /* Check for error or file end or line end */ if(read_count <= 0 || dest[line_position] == '\n') { /* Error -> return error */ if(ferror(file)) { return -1; } else { /* line or file end, override with string end and break */ break; } } line_position++; } /* Set last char in line to 0 to indicate string end */ dest[line_position] = 0; return line_position; }
C
/** * @file * */ #pragma once #include "pebble.h" /** * Read what configuration data we have from watch flash into RAM cache. * Best called from program init, as this might be a lengthy operation. */ void config_data_init(); /** * Convenience function to simply check whether location data is persisted, * without returning the values. * * @return \c true if persisted location info is available, else \c false. */ bool config_data_location_avail(); /** * Has timezone offset changed since our last check. * Intended to detect whether the Pebble has changed its DST flag, or been * updated by the phone. * * Only makes sense in SDK v3 and later, since that is when Pebble first (!) * added true on-watch support for timezones and DST. */ #ifndef PBL_SDK_2 bool config_has_tz_offset_changed(); #endif /** * Read location data from our watch-based persistent storage. * * Any of the supplied output pointers may be NULL if the caller is not * interested in the particular field. * * @param pLat Points to var to receive latitude coord: degrees from equator, * positive for North, negative for South. * @param pLong Points to var to receive longitude coord: degrees from * Greenwich, positive for East, negative for West. * @param pUtcOffset Points to var to receive offset of local (watch) time * from UTC, in seconds. This is the reverse of the usual tz * offset: *pUtcOffset is added to local time to obtain UTC. * @param pLastUpdateTime Points to var to receive the time the returned values * were last changed in flash. This is relative to PebbleOS' time() * value, so is local time rather than UTC. * * @return \c true if persisted location info is available, else \c false. * In the latter case, all other returns are undefined. */ //bool config_data_location_get(float* pLat, float *pLong, int32_t *pUtcOffset, // time_t* pLastUpdateTime); /** * Returns most recent latitude fed us by the phone. * * @return Degrees from equator. Positive for North, negative for South. */ float config_data_get_latitude(); /** * Returns most recent longitude fed us by the phone. * * @return Degrees from Greenwich. Positive for East, negative for West. */ float config_data_get_longitude(); /** * Returns timezone offset. * * @return Offset of time from UTC, in hours. Add this to UTC to obtain local time. */ float config_data_get_tz_in_hours(); /** * Convenience to check if the caller-supplied values match our config values. * * @param fLat Latitude coord: degrees from equator, positive for North, * negative for South. * @param fLong Longitutde coord: degrees from Greenwich, positive for East * and negative for West. * @param pUtcOffset Offset of local (watch) time from UTC, in seconds. * This is the reverse of the usual tz offset: *pUtcOffset * is added to local time to obtain UTC. * * @return \c true of parameters match our config, else \c false. */ bool config_data_is_different(float latitude, float longitude, int32_t utcOffset); /** * Save supplied location values in our cache and in watch flash. * This is a blocking call and the flash write might take a noticable * amount of time, so design accordingly. * * @param fLat Latitude coord: degrees from equator, positive for North, * negative for South. * @param fLong Longitutde coord: degrees from Greenwich, positive for East * and negative for West. * @param pUtcOffset Offset of local (watch) time from UTC, in seconds. * This is the reverse of the usual tz offset: *pUtcOffset * is added to local time to obtain UTC. * * @return \c true if write went ok, \c false if it failed. */ bool config_data_location_set(float fLat, float fLong, int32_t iUtcOffset); /** * Remove location configuration data from watch flash. Intended for testing, * this is also a blocking call and likely as slow as flash write. */ void config_data_location_erase(void);
C
#include <stdio.h> long function(long a, long b) { long x = a, y = b; return (x + y); } int main(int argc, char* argv[]) { long a = 1, b = 2; printf("%d\n", function(a, b)); return 0; }
C
/* // Copyright (c) 2010-2017 Intel Corporation // // 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. */ #ifndef _LOCAL_MBUF_H_ #define _LOCAL_MBUF_H_ #define LOCAL_MBUF_COUNT 64 struct local_mbuf { struct rte_mempool *mempool; uint32_t n_new_pkts; struct rte_mbuf *new_pkts[LOCAL_MBUF_COUNT]; }; static struct rte_mbuf **local_mbuf_take(struct local_mbuf *local_mbuf, uint32_t count) { PROX_ASSERT(local_mbuf->n_new_pkts >= count); const uint32_t start_pos = local_mbuf->n_new_pkts - count; struct rte_mbuf **ret = &local_mbuf->new_pkts[start_pos]; local_mbuf->n_new_pkts -= count; return ret; } static int local_mbuf_refill(struct local_mbuf *local_mbuf) { const uint32_t fill = LOCAL_MBUF_COUNT - local_mbuf->n_new_pkts; struct rte_mbuf **fill_mbuf = &local_mbuf->new_pkts[local_mbuf->n_new_pkts]; if (rte_mempool_get_bulk(local_mbuf->mempool, (void **)fill_mbuf, fill) < 0) return -1; local_mbuf->n_new_pkts += fill; return 0; } /* Ensures that count or more mbufs are available. Returns pointer to count allocated mbufs or NULL if not enough mbufs are available. */ static struct rte_mbuf **local_mbuf_refill_and_take(struct local_mbuf *local_mbuf, uint32_t count) { PROX_ASSERT(count <= LOCAL_MBUF_COUNT); if (local_mbuf->n_new_pkts >= count) return local_mbuf_take(local_mbuf, count); if (local_mbuf_refill(local_mbuf) == 0) return local_mbuf_take(local_mbuf, count); return NULL; } #endif /* _LOCAL_MBUF_H_ */
C
#include <stdio.h> #define NL 20 #define NC 76 char space[NL][NC]; char space1[NL][NC]; display (char space[NL][NC]) { int l, c; gotoxy (1, 1); printf ("\n"); for (l=0; l<NL; l++) { for (c=0; c<NC; c++) { if (space[l][c] > 0) printf ("#"); else printf ("."); } printf ("\n"); } } int n_voisins (char space[NL][NC], int l, int c) { int n, i, j; n = 0; for (i=-1; i<=1; i++) for (j=-1; j<=1; j++) n += space[l+i][c+j]; return n; } step (char space[NL][NC]) { int l, c, n; /* char space1[NL][NC]; */ for (l=1; l<NL-1; l++) for (c=1; c<NC-1; c++) { n = n_voisins (space, l, c); if (space[l][c] <= 0) { if (n == 3) space1[l][c] = 1; else space1[l][c] = 0; } else { if (n == 3 || n == 4) space1[l][c] = 1; else space1[l][c] = 0; } } memcpy (space, space1, NL*NC /*sizeof(space)*/); } main (int argc, char *argv[]) { FILE *f; int l, c; int ch; if (argc != 2) { printf ("Usage: LIFE filename\n"); return; } for (l=0; l<NL; l++) for (c=0; c<NC; c++) { space[l][c] = 0; space1[l][c] = 0; } f = fopen (argv[1], "r"); if (f == NULL) { perror (argv[1]); } else { l = 1; c = 1; for (;;) { ch = getc (f); if (feof(f)) break; if (ch == '\n') { l++; c = 1; } else if (ch == '.' || ch == ' ') { space[l][c++] = 0; } else { space[l][c++] = 1; } } clrscr (); for (;;) { display (space); while (!kbhit()); getch(); step (space); } } } 
C
#include<stdio.h> int main(void){ int num[5][5]={{2,1,3,2,5},{1,2,6,1,0},{4,0,0,0,2},{5,6,7,8,0},{1,0,1,1,0}}; int i,j,n; for(i=0;i<=4;i++){ for(j=0;j<=4;j++){ n=(num[i][j]==0); num[i][j]=n; printf("%d ",num[i][j]); } printf("\n"); } return 0; }
C
#include <stdio.h> #include <stdlib.h> int add(int a, int b) { return a + b; } int sub(int a, int b) { return a - b; } void program_usage(char *prog_name) { printf("%s <add/sub> num1 num2\n"); } int main(int argc, char **argv) { if (argc != 4) { program_usage(argv[0]); return -1; } if (!strcmp(argv[1], "add")) { printf("add result %d\n", add(atoi(argv[2]), atoi(argv[3]))); } else if (!strcmp(argv[1], "sub")) { printf("sub result %d\n", sub(atoi(argv[2]), atoi(argv[3]))); } else { program_usage(argv[0]); return -1; } return 0; }
C
#include <stdio.h> #include <string.h> #include "sensorIR.h" #include "train.h" #include "model.h" #include "railway.h" #include "crossingGate.h" #include "semaphore.h" #include "trafficLight.h" #define MAX_OBJS 100 static struct object_ref_t { observable_t* obs; const char* name; } objs[MAX_OBJS]; static int n_objs = 0; int model_add_observable(const char* name, observable_t* obs) { if (n_objs <= MAX_OBJS) { objs[n_objs].name = name; objs[n_objs].obs = obs; n_objs++; return 1; } printf("Max. sensor registered\n"); return 0; } void model_init(void) { static struct ir_name_t { const char* name; } ir_names[] = { { "IRsensor0" }, { "IRsensor1" }, { "IRsensor2" }, { "IRsensor3" }, { NULL } }; static struct train_name_t { const char* name; } train_names[] = { { "Diesel" }, { "Renfe" }, { NULL } }; static struct railway_name_t { const char* name; } railway_names[] = { { "via0" }, { NULL } }; static struct crossingGate_name_t { const char* name; } crossingGate_names[] = { { "barrera0" }, { NULL } }; static struct trafficlight_name_t { const char* name; } trafficlight_names[] = { { "semaforotrafico0" }, { NULL } }; static struct semaphore_name_t { const char* name; } semaphore_names[] = { { "semaforo0" }, { "semaforo1" }, { "semaforo2" }, { "semaforo3" }, { NULL } }; int i = 0; struct ir_name_t* s; struct train_name_t* t; struct railway_name_t* r; struct crossingGate_name_t* cr; struct trafficlight_name_t* tl; struct semaphore_name_t* sph; for (s = ir_names; s->name; ++s) { model_add_observable(s->name, (observable_t*) sensors[i]); i++; } i = 0; for (t = train_names; t->name; ++t) { model_add_observable(t->name, (observable_t*) trains[i]); i++; } i = 0; for (r = railway_names; r->name; ++r) { model_add_observable(r->name, (observable_t*) railways[i]); i++; } i = 0; for (cr = crossingGate_names; cr->name; ++cr) { model_add_observable(cr->name, (observable_t*) crossingGates[i]); i++; } i = 0; for (tl = trafficlight_names; tl->name; ++tl) { model_add_observable(tl->name, (observable_t*) trafficLights[i]); i++; } i = 0; for (sph = semaphore_names; sph->name; ++sph) { model_add_observable(sph->name, (observable_t*) semaphores[i]); i++; } i = 0; } observable_t* model_get_observable(const char* name) { struct object_ref_t* o; for (o = objs; o->name; ++o) { if (0 == strcmp(name, o->name)) return o->obs; } printf("observable not found \n"); return NULL; }
C
#include "../base.h" int main(){ void *context=zmq_ctx_new(); void *receiver=zmq_socket(context, ZMQ_PULL); int rc=zmq_bind(receiver, "tcp://*:5558"); assert(rc==0); void *controller=zmq_socket(context, ZMQ_PUB); rc=zmq_bind(controller, "tcp://*:5559"); assert(rc==0); char string[256]; s_recv(receiver, string, 256); int64_t start_time; s_clock(&start_time); int task_nbr; for (task_nbr=0; task_nbr<100; ++task_nbr){ s_recv(receiver, string, 256); if (task_nbr%10==0){ printf(":"); } else{ printf("."); } fflush(stdout); } int64_t end_time; s_clock(&end_time); printf("Total elapsed time: %d msec\n", (int)(end_time-start_time)); s_send(controller, "KILL", 0, NULL); zmq_close(controller); zmq_close(receiver); zmq_ctx_destroy(context); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <limits.h> #include "kw26.h" // print an Int40 (followed by a newline character) void kw26Print(Int40 *p) { int i; if (p == NULL) { printf("(null pointer)\n"); return; } for (i = MAX40 - 1; i >= 0; i--) printf("%x", p->digits[i]); printf("\n"); } int main(int argc, char *argv[]) { Int40 *p; Int40 *q; Int40 *r; int seed = 0; int fNum = 0; char *cryptoFilename; // Check if command line parms entered // IF none ->EXIT but leave a message if (argc == 1) { printf("\n\t usage:\n"); printf("\t kw26-m4 fibonacciNumber cryptoFilename seedType\n\n"); exit(1); } fNum = atoi(argv[1]); cryptoFilename = argv[2]; seed = atoi(argv[3]); // Load crypto variable from the file named cryptoFilename // Load the HW config variable F[0] p = loadHWConfigVariable(seed); // Load the Crypto Variable F[1] q = loadCryptoVariable(cryptoFilename); r = fibKw26(fNum, p, q); kw26Print(p); //print HW config variable F[0] kw26Print(q); //print crypto variable F[1] kw26Print(r); //print F[n] kw26Rating(); //print the rating (NID,difficulty, & hours) return 0; }
C
void Inner(int Lower, int Middle, int Upper) { int i; int A[Middle-Lower+1]; int B[Upper-Middle+1]; for (i=0; i< Middle-Lower+1;i++) A[i] = i; for (i=0; i < Upper-Middle+1; i++) B[i] = i; for (i=0; i < Upper-Middle+1; i++) B[i] = A[i % (Middle-Lower+1)]; } int main() { Inner(1, 15, 30); };
C
/****************************** (C) COPYRIGHT 2016 ******************************* * * ܣ * Ҫ㣺̿ƣmathãҪעĽ˼·ص㡣 * ص㣺ǰģ˺϶ڵĴѭʵ * Ǵ-1~1иɶݵġÿжӦλþҪǺˣע * һжӦ㣬acosֻһ㣬ڶƵݾ庯 * ********************************************************************************/ #include <stdio.h> #include <math.h> #define PI 3.14 void PrintCos(char f_sym, int f_x); void PrintSin(char f_sym, int f_x); /************************************************* Function: main Description: Calls: scanf printf Called By: Input: Output: Return: 0 *************************************************/ int main(void) { char sym; int x; printf("input the symbol:\n"); scanf("%c %d", &sym, &x); PrintCos(sym, x); printf("\n"); PrintSin(sym, x); } /************************************************* Function: PrintCos Description: cosӡ Calls: printf Called By: main Input: Output: Return: 0 *************************************************/ void PrintCos(char f_sym, int f_x) { float i; int j; int a, b; //forдѭԼǺСֵϵ for (i = 1.0; i > -1.0; i -= 0.1) { a = (int)(acos(i) * f_x); //رע2a1aǶӦ꣬ //ΪһǰѾճλ b = (int)(2 * PI * f_x) - a * 2; for (j = 0; j < a; j++) printf(" "); printf("%c", f_sym); for (j = 0; j < b; j++) printf(" "); printf("%c", f_sym); printf("\n"); } } /************************************************* Function: PrintCos Description: cosӡ Calls: printf Called By: main Input: Output: Return: 0 *************************************************/ void PrintSin(char f_sym, int f_x) { float i; int j; int a, b; //Һ贫ηֱ for (i = 1.0; i > 0; i -= 0.1) { a = (int)(asin(i) * f_x); b = (int)(PI * f_x) - a * 2; for (j = 0; j < a; j++) printf(" "); printf("%c", f_sym); for (j = 0; j < b; j++) printf(" "); printf("%c", f_sym); printf("\n"); } for (i = 0; i > -1; i -= 0.1) { a = (int)((PI - asin(i)) * f_x); b = (int)(3 * PI * f_x) - a * 2; // for (j = 0; j < int(PI * f_x); j++) // printf(" "); for (j = 0; j < a; j++) printf(" "); printf("%c", f_sym); for (j = 0; j < b; j++) printf(" "); printf("%c", f_sym); printf("\n"); } }
C
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #define MYFIFO "./record_for_client" #define BUFFER_SIZE 1024 int main() { char buf[BUFFER_SIZE]; int fd,nread; if(access(MYFIFO, F_OK)==-1) { if((mkfifo(MYFIFO,0666)<0)&&(errno != EEXIST)) { printf("Cannot create fifo file\n"); exit(1); } } if((fd=open(MYFIFO,O_RDONLY))==-1) { printf("Open fifo file error\n"); exit(1); } while(1) { memset(buf,0,BUFFER_SIZE); if((nread=read(fd,buf,BUFFER_SIZE))>0) { printf("%s\n",buf); } } close(fd); exit(0); }
C
#include "shell.h" /** * path_append - Append program or command to the path * @path: PATH directory * @cmd: program file or command * Return: pointer to a PATH newly string or NULL on failure */ char *path_append(char *path, char *cmd) { int len_path = 0, len_cmd = 0; char *full_path; if (path == NULL) path = ""; if (cmd == NULL) cmd = ""; full_path = malloc(((_strlen(path) + _strlen(cmd)) * sizeof(char)) + 2); if (full_path == NULL) return (NULL); while (path[len_path]) { full_path[len_path] = path[len_path]; len_path++; } if (path[len_path - 1] != '/') { full_path[len_path] = '/'; len_path++; } while (cmd[len_cmd]) { full_path[len_path + len_cmd] = cmd[len_cmd]; len_cmd++; } full_path[len_path + len_cmd] = '\0'; free_function(1, cmd); return (full_path); }
C
#include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include <time.h> #include <math.h> #include <sys/ioctl.h> #include <unistd.h> /* * KwPBar for C, v0.2.0 * Copyright © 2013-2018, Chris Warrick. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions, and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the author of this software nor the names of * contributors to this software may be used to endorse or promote * products derived from this software without specific prior written * consent. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ int get_termlength() { struct winsize w; ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); return w.ws_col; } int pbar(double value, double max) { int fullwidth = get_termlength(); int pbarwidth = fullwidth - 9; double progress; if (max == 0) { fprintf(stderr, "ERROR: invalid progressbar maximum (0)\n"); return 1; } else { progress = value / max; } // calculate percentage double perc = progress * 100; char percs[10]; sprintf(percs, " %4.1f", perc); // calculate things to display int now = round(progress * pbarwidth); char bar[fullwidth]; memset(bar, '\0', sizeof(bar)); memset(bar, ' ', pbarwidth); if (progress == 1) { memset(bar, '=', now); } else if (progress < 0 || progress > 1) { fprintf(stderr, "ERROR: invalid progressbar value (not in range [0, 1])\n"); return 2; } else if (progress != 0) { memset(bar, '=', now - 1); bar[now - 1] = '>'; } fprintf(stderr, "\r[%s]%s%%", bar, percs); return 0; } void erase_pbar() { int fullwidth = get_termlength(); char bar[fullwidth]; memset(bar, '\0', sizeof(bar)); memset(bar, ' ', fullwidth); fprintf(stderr, "\r%s\r", bar); }
C
/*------------------------------------------------------------------------ * * geqo_pool.c * Genetic Algorithm (GA) pool stuff * * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * src/backend/optimizer/geqo/geqo_pool.c * *------------------------------------------------------------------------- */ /* contributed by: =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*= * Martin Utesch * Institute of Automatic Control * = = University of Mining and Technology = * [email protected] * Freiberg, Germany * =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*= */ /* -- parts of this are adapted from D. Whitley's Genitor algorithm -- */ #include "postgres.h" #include <float.h> #include <limits.h> #include <math.h> #include "optimizer/ants_copy.h" #include "optimizer/ants_pool.h" /* * alloc_pool * allocates memory for GA pool */ Ants init_Ants(int nodeInitial) { Ants newAnts; newAnts.beginState=(int)nodeInitial; newAnts.tourMemory=(int *)malloc(1*sizeof(int)); newAnts.tourMemory[0]=nodeInitial; newAnts.cantState=1; newAnts.cost=0; return newAnts; } /*Calcula el costo de ir del estado en el que estoy a todos los que faltan por recorrer luego divide cada costo individual entre la suma de todos y elije uno con la ruleta */ //void setNextStep(Ants ants, double **matrixWeight,double **matrixPheromone, int sizeProblem, int alpha, int beta) void setNextStep(PlannerInfo * root,Ants *ants, int sizeProblem, int alpha, int beta) { double sumAj=0; double arrayTemp[sizeProblem]; int currentState=ants->tourMemory[ants->cantState-1]; int i; double temp=0; double aux=0; double pheromone; int resultState; for(i=0; i<sizeProblem; i++) { if(!visited(*ants,i)) { //se le resta 1 a currentState porque los valores de los estados son numeros desde 1 a sizeProblem incluyendo ambos n�meros pheromone=matrixPheromone[currentState-1][i]; aux=1/matrixWeight[currentState-1][i]; temp=exponential(pheromone, alpha) * exponential(aux, beta); sumAj+=temp; } arrayTemp[i]=temp; temp=0;//esto los puse para que los estados que ya han sido visitados tengan valor 0 } for (i = 0; i < sizeProblem; i++) { arrayTemp[i] /= sumAj; } resultState = ruleta(root,arrayTemp,sizeProblem); //se le suma 1 a resultState porque los valores de los estados son numeros desde 1 a sizeProblem incluyendo ambos n�meros setState(ants,resultState+1); } int visited(Ants ants,int state) { int i=0; while(i<ants.cantState) { if(state==(ants.tourMemory[i]-1)) return 1; i++; } return 0; } double exponential(double base, int exponente) { double result = 1; int i; for (i = 0; i < exponente; i++) { result *= base; } return result; } void setState(Ants *ants,int state) { int *tour=ants->tourMemory; int length=ants->cantState; int *temp=malloc(sizeof(int)*(length+1)); int i; for(i=0; i<length; i++) { temp[i]=tour[i]; } temp[i]=state; ants->cantState=length+1; ants->tourMemory=temp; } //double calculateCoste(Ants ants,double **matrixWeight) double calculateCoste(int *tour,int lengthTour) { //int *tour=ants.tourMemory; int i; double cost=0; for(i=0;i<lengthTour-1;i++) { cost+=matrixWeight[tour[i]][tour[i+1]]; } return cost; }
C
#ifndef _AGENTE_H_ #define _AGENTE_H_ #include "ambiente.h" // define o pontuação caso o agente encontre o // ouro. #define PREMIUM 1000 // define a penalidade sobre o agente caso // seja atirado uma flecha. #define THROW_ARROW -10 #define hash(linha, coluna) ((linha) * 10) + (coluna) typedef enum ACAO{ ANDAR, ATIRAR, PEGAR } ACAO; typedef enum SENTIDO{ NORTE, LESTE, SUL, OESTE } SENTIDO; typedef struct Personagem{ int linha; int coluna; int contador_movimento; int pontos; int flecha; SENTIDO direcao; char mundo_conhecido[TAM_MAPA][TAM_MAPA]; } Personagem; Personagem player; //extern int verifica_estado(); extern char mapa[TAM_MAPA][TAM_MAPA]; void inicializa_jogador(); ///Altera o atributo pontos do agente. (similar um set). void pontuar(int pontos); /** * Altera as "coordenadas" x e y do agente. Realiza a movimentação do agente e * aplica penalização. */ void andar(SENTIDO sentido); ///Altera a direção (NORTE, SUL, LESTE e OESTE) do agente e aplica penalização. void rotacionar(SENTIDO newSentido); ///Aplica pontuação final para o agente e remove ouro do mapa. (FLAG PREMIUM). void pegarOuro(); /** * Remove o wumpus do mapa e aplica penalização ao agente por atirar a flecha. * (FLAG THROW_AXE) */ void atirarFlecha(SENTIDO sentido); /** * Identifica qual ação deve ser tomada (ROTATE, ANDAR, ATIRAR, PEGAR) e chama a * função respectiva.*/ void agir(ACAO acao, SENTIDO sentido); ///Utiliza o mundo conhecido para tentar deduzir o que existe no mapa. int marcar_estados_adj(); ///Define a ação que o agente irá tomar int gera_acao(char pai[TAM_MAPA * TAM_MAPA], int ultimo); /** * Imprime na tela um pequeno mapa com todas as informações que o jogador * conhece. */ void imprime_mundo_conhecido(); /** * Exibe uma mensagem na tela e encerra o jogo mostrando a pontuação final do * agente. */ void finaliza(const char *mensagem); #endif /*_AGENTE_H_*/
C
/* ** EPITECH PROJECT, 2017 ** [email protected] ** File description: ** fonction.c */ #include "../include/my.h" #include "../include/lib.h" void my_print_map(char **map) { int nb = 0; while(map[nb][0] != '\0') { printw(map[nb]); nb = nb + 1; } } int my_collision_check(int y, int x, char **map) { if (map[y][x] == ' ' || map[y][x] == 'O') return (1); else if (map[y][x] == 'X') return (2); else if (map[y][x] == '#') return (-1); return (0); } int *get_pos_player(char **map, char c) { int *pos = malloc(sizeof(int) * 10); int y = 0; int x = 0; int nb = 0; while (map[y][x] != '\0') { if (map[y][x] == c) { pos[nb] = y; pos[nb+1] = x; nb = nb + 2; } x = x + 1; if (map[y][x] == '\n') { x = 0; y = y + 1; } } pos[nb] = -1; return (pos); } int my_win_lose(char **map, int total, int *circles) { int *boxes = get_pos_player(map, 'X'); int win = 0; int lose = 0; int nb = 0; while (circles[nb] != -1 && boxes[nb] != -1) { if (circles[nb] == boxes[nb] && circles[nb + 1] == boxes[nb + 1]) { win = win + 1; } if (map[boxes[nb] - 1][boxes[nb + 1]] == '#' && map[boxes[nb]][boxes[nb + 1] + 1] == '#') { lose = lose + 1; } if (map[boxes[nb] + 1][boxes[nb + 1]] == '#' && map[boxes[nb]][boxes[nb + 1] + 1] == '#') { lose = lose + 1; } if (map[boxes[nb] + 1][boxes[nb + 1]] == '#' && map[boxes[nb]][boxes[nb + 1] - 1] == '#') { lose = lose + 1; } if (map[boxes[nb] - 1][boxes[nb + 1]] == '#' && map[boxes[nb]][boxes[nb + 1] - 1] == '#') { lose = lose + 1; } if (lose == total) { clear(); printw("You Lost!"); refresh(); sleep(2); free(map); endwin(); exit(1); } if (win == total) { clear(); printw("You Won!"); refresh(); sleep(2); free(map); endwin(); exit(0); } nb = nb + 2; } return (0); } int my_total_count(char **map) { int circles = 0; int boxes = 0; int y = 0; int x = 0; while (map[y][x] != '\0') { if (map[y][x] == 'O') { circles = circles + 1; } if (map[y][x] == 'X') { boxes = boxes + 1; } x = x + 1; if (map[y][x] == '\n') { x = 0; y = y + 1; } } return (boxes); }
C
char * addBinary(char * a, char * b){ int iLengthOfa = strlen(a); int iLengthOfb = strlen(b); int iCarry = 0; int iIndexOfa = iLengthOfa; int iIndexOfb = iLengthOfb; int iMax = (iIndexOfa>iIndexOfb?iIndexOfa:iIndexOfb)+1;//?:必须加(),不然最后iIndexOfb+1会当做整体 char *sRet = malloc((iMax+1)*sizeof(char)); memset(sRet,0,(iMax+1)*sizeof(char)); while(iIndexOfa>0||iIndexOfb>0||iCarry>0) { sRet[iMax-1] = ((iIndexOfa >0?(a[iIndexOfa-1]-48):0) + (iIndexOfb >0?(b[iIndexOfb-1]-48):0) + iCarry)%2 + 48; iCarry = ((iIndexOfa >0?(a[iIndexOfa-1]-48):0) + (iIndexOfb >0?(b[iIndexOfb-1]-48):0) + iCarry)/2; iMax--; if(iIndexOfa>0) { iIndexOfa--; } if(iIndexOfb>0) { iIndexOfb--; } } if(iMax) { return (sRet+1); } else { return sRet; } }
C
int main(){ int n,i,j,count; char dna[256]; scanf("%d",&n); gets(dna); for(i=0;i<n;i++){ gets(dna); count=strlen(dna); for(j=0;j<count;j++){ if(dna[j]=='A') printf("T"); else if(dna[j]=='T') printf("A"); else if(dna[j]=='C') printf("G"); else if(dna[j]=='G') printf("C"); } printf("\n"); } return 0; }
C
#include <stdio.h> #include <stdlib.h> typedef struct data{ int dia, mes, ano; }niver; typedef struct tad{ char nome[20]; niver data; int cpf; }dados; void armazenar (dados *p); void imprimir (dados *p); int main(){ dados p; //p = (dados *) malloc(sizeof(dados)); armazenar(&p); imprimir(&p); return 0; } void armazenar (dados *p){ printf("Nome: "); scanf(" %[^\n]s",p->nome); printf("Data de nascimento (dia,mes,ano): "); scanf("%d", &p->data.dia); scanf("%d", &p->data.mes); scanf("%d", &p->data.ano); printf("CPF: "); scanf("%d", &p->cpf); } void imprimir (dados *p){ printf("Nome: %s\n", p->nome); printf("Data de nascimento: %d/%d/%d\n", p->data.dia,p->data.mes,p->data.ano); printf("CPF: %d\n", p->cpf); }
C
#include "Header.h" /************************************************************* * Function: display_menu * * Date Created: 10/18/7 * * Date Last Modified: 10/18/17 * * Description: Displays the menu * Input parameters: * * Returns: * * Preconditions: * * Postconditions: None * *************************************************************/ void display_menu(void) { printf("1.Game Rules\n"); printf("2.Start Game\n"); printf("3.End Game\n"); } /************************************************************* * Function: get_option * * Date Created: 10/18/7 * * Date Last Modified: 10/18/17 * * Description: gets the option of the user * Input parameters: * * Returns: * * Preconditions: * * Postconditions: None * *************************************************************/ int get_option(void) { int option = 0, status = 0; status = scanf("%d", &option); // status = fscanf (infile, "%d", &n1); // if (status == EOF) if (status == 0) { printf("Failed at reading in an integer!\n"); } return option; } /************************************************************* * Function: determine option * * Date Created: 10/18/7 * * Date Last Modified: 10/18/17 * * Description: gets the option * Input parameters: * * Returns: * * Preconditions: * * Postconditions: None * *************************************************************/ int determine_option(void) { int option = 0; do // input validation loop { display_menu(); option = get_option(); system("cls"); } while ((option < 1) || (option > 3)); return option; } /************************************************************* * Function: start game * * Date Created: 10/18/17 * * Date Last Modified: 12/1/17 * * Description: plays the game * Input parameters: int *die1, int *die2, int *die3, int *die4, int *die5,int *die6, int *p1, int *p2, int *p3, int *p4, int *p5,int *p6, int ones, int twos, int threes, int fours, int fives, int sixes, int th_kind, int fo_kind, int fu_house, int sma_straight, int lar_straight,int yahtzee1,int chan * * Returns: * * Preconditions: * * Postconditions: None * *************************************************************/ int start_game(int *die1, int *die2, int *die3, int *die4, int *die5,int *die6, int *p1, int *p2, int *p3, int *p4, int *p5,int *p6, int ones, int twos, int threes, int fours, int fives, int sixes, int th_kind, int fo_kind, int fu_house, int sma_straight, int lar_straight,int yahtzee1,int chan) { int first_die[5]; int option1 = 0, option2 = 0, option3 = 0, option4 = 0, option5 = 0, option6 = 0, option7 = 0, option8 = 0, option9 = 0, option10 = 0, option11 = 0, option12 = 0; //int a[5]; int roll_die = 1; int amount = 1; int num_rolls = 1; int num_count = 0; int user_input_for_yes_or_no = 0; int user_option = 0; int die_total = 0; int start = 0; int rolls = 1; int player_points = 0; int player_total=0 ; printf("Die value 1 is %d\n", *die1); printf("Die value 2 is %d\n", *die2); printf("Die value 3 is %d\n", *die3); printf("Die value 4 is %d\n", *die4); printf("Die value 5 is %d\n", *die5); printf("Die value 6 is %d\n", *die6); printf("To make it easier for you\nThe numbers will now be in order\n"); printf("Die value 1 is %d\n", *p1); printf("Die value 2 is %d\n", *p2); printf("Die value 3 is %d\n", *p3); printf("Die value 4 is %d\n", *p4); printf("Die value 5 is %d\n", *p5); printf("Die value 6 is %d\n", *p6); player_total = player_points + player_total; printf("You have %d points so far\n", player_total); for (; rolls < 3; rolls++) { printf("\n"); printf("You are on roll %d\n", rolls); printf("\n"); /* initialize elements of array n to 0 */ printf("Would you like to roll for one of the game's combinations?\n"); printf("Input 1 for yes and 2 for no\n"); scanf(" %d", &user_input_for_yes_or_no); if (user_input_for_yes_or_no == 1) { printf("Please input the combination you would like\n"); scanf("%d", &user_option); printf("Okay your option is %d\n", user_option); printf("\n"); if (user_option == 1) { printf("You got a score of %d\n", ones); player_points = ones; return 0; } if (user_option == 2) { printf("You got a score of %d\n", twos); player_points = twos; return 0; } if (user_option == 3) { printf("You got a score of %d\n", threes); player_points = threes; return 0; } if (user_option == 4) { printf("You got a score of %d\n", fours); player_points = fours; return 0; } if (user_option == 5) { printf("You got a score of %d\n", fives); player_points = fives; return 0; } if (user_option == 6) { printf("You got a score of %d\n", sixes); player_points = sixes; return 0; } if (user_option == 7) { printf("You got a score of %d\n", th_kind); player_points = th_kind; return 0; } if (user_option == 8) { printf("You got a score of %d\n", fo_kind); player_points = fo_kind; return 0; } if (user_option == 9) { printf("You got a score of %d\n", fu_house); player_points = fu_house; return 0; } if (user_option == 10) { printf("You got a score of %d\n", sma_straight); player_points = sma_straight; player_total = player_points + player_total; printf("You have %d points so far\n", player_total); return 0; } if (user_option == 11) { printf("You got a score of %d\n", lar_straight); player_points = lar_straight; return 0; } if (user_option == 12) { printf("You got a score of %d\n", yahtzee1); player_points = yahtzee1; return 0; } if (user_option == 13) { printf("You got a score of %d\n", chan); player_points = chan; return 0; } } player_total = player_points + player_total; printf("You have %d points so far\n", player_total); if (user_input_for_yes_or_no == 2) { printf("Okay, i will ask one more time later\n\n"); printf("Please note, if you do not choose a combination by your 3rd chance\nYou will recieve 0 points for that round\n"); printf("If you want to reroll on a die press <1> for yes and <2> for no\n"); //1 printf("Would you like to re-roll die 1?\n"); scanf("%d", &option1); if (option1 == 1) { *die1 = rand() % 6 + 1; } //2 printf("Would you like to re-roll die 2?\n"); scanf("%d", &option2); if (option2 == 1) { *die2 = rand() % 6 + 1; } //3 printf("Would you like to re-roll die 3?\n"); scanf("%d", &option3); if (option3 == 1) { *die3 = rand() % 6 + 1; } //4 printf("Would you like to re-roll die 4?\n"); scanf("%d", &option4); if (option4 == 1) { *die4 = rand() % 6 + 1; } //5 printf("Would you like to re-roll die 5?\n"); scanf("%d", &option5); if (option5 == 1) { *die5 = rand() % 6 + 1; } //6 printf("Would you like to re-roll die 6?\n"); scanf("%d", &option6); if (option6 == 1) { *die6 = rand() % 6 + 1; } } if (rolls > 3) { player_points = 0; printf("You got zero points\n"); return 0; } } if (player_total > 63) { player_total = player_total + 35; printf("You won!\nWith the score of %d\n",player_total); //return 0; exit(0); } } /************************************************************* * Function: start game ai * * Date Created: 12/1/17 * * Date Last Modified: 12/1/17 * * Description: ai plays the game * Input parameters: int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6, int ai_ones, int ai_twos, int ai_threes, int ai_fours, int ai_fives, int ai_sixes, int ai_th_kind, int ai_fo_kind, int ai_fu_house, int ai_sma_straight, int ai_lar_straight, int ai_yahtzee1, int ai_chan * * Returns: * * Preconditions: * * Postconditions: None * *************************************************************/ int start_game_ai(int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6, int ai_ones, int ai_twos, int ai_threes, int ai_fours, int ai_fives, int ai_sixes, int ai_th_kind, int ai_fo_kind, int ai_fu_house, int ai_sma_straight, int ai_lar_straight, int ai_yahtzee1, int ai_chan) { printf("Now the ai will play\n"); int ai_option = 0; int ai_points = 0, ai_total = 0; ai_option = rand() % 13 + 1; if (ai_option == 1) { printf("ai got a score of %d\n", ai_ones); ai_points = ai_ones; return 0; } if (ai_option == 2) { printf("ai got a score of %d\n", ai_twos); ai_points = ai_twos; return 0; } if (ai_option == 3) { printf("ai got a score of %d\n", ai_threes); ai_points = ai_threes; return 0; } if (ai_option == 4) { printf("ai got a score of %d\n", ai_fours); ai_points = ai_fours; return 0; } if (ai_option == 5) { printf("ai got a score of %d\n", ai_fives); ai_points = ai_fives; return 0; } if (ai_option == 6) { printf("ai got a score of %d\n", ai_sixes); ai_points = ai_sixes; return 0; } if (ai_option == 7) { printf("ai got a score of %d\n", ai_th_kind); ai_points = ai_th_kind; return 0; } if (ai_option == 8) { printf("ai got a score of %d\n", ai_fo_kind); ai_points = ai_fo_kind; return 0; } if (ai_option == 9) { printf("ai got a score of %d\n", ai_fu_house); ai_points = ai_fu_house; return 0; } if (ai_option == 10) { printf("ai got a score of %d\n", ai_sma_straight); ai_points = ai_sma_straight; return 0; } if (ai_option == 11) { printf("ai got a score of %d\n", ai_lar_straight); ai_points = ai_lar_straight; return 0; } if (ai_option == 12) { printf("ai got a score of %d\n", ai_yahtzee1); ai_points = ai_yahtzee1; return 0; } if (ai_option == 13) { printf("ai got a score of %d\n", ai_chan); ai_points = ai_chan; return 0; } ai_total = ai_points + ai_total; printf("\n"); printf("Ai have %d points so far\n", ai_total); printf("\n"); if (ai_total > 63) { ai_total = ai_total + 35; printf("Ai won!\nWith the score of %d\n", ai_total); //return 0; exit(0); } } /************************************************************* * Function: print combination * * Date Created: 11/29/17 * * Date Last Modified: 11/29/17 * * Description: prints out the available combinations * Input parameters: * * Returns: * * Preconditions: * * Postconditions: None * *************************************************************/ void print_combination(void) { printf("1. Sum of 1's\t7. Three-of-a-kind\n2. Sum of 2's\t8. Four-of-a-kind\n3.Sum of 3's\t9.Full house\n4. Sum of 4's\t 10.Small straight\n5.Sum of 5's\t 11.Large straight\n6.Sum of 6's\t12. Yahtzee\n13.Chance\n"); } /************************************************************* * Function: get_die_values This is for the Player * * Date Created: 11/29/17 * * Date Last Modified: 11/29/17 * * Description: gets the possible combinations for die_values * Input parameters: int *die1, int *die2, int *die3, int *die4, int *die5 * * Returns: int * * Preconditions: * * Postconditions: None * *************************************************************/ int get_die_values(int *die1, int *die2, int *die3, int *die4, int *die5,int *die6) { *die1 = rand() % 6+1; *die2 = rand() % 6+1; *die3 = rand() % 6+1; *die4 = rand() % 6+1; *die5 = rand() % 6+1; *die6 = rand() % 6+1; } /************************************************************* * Function: get_die_values_ai This is for the ai * * Date Created: 11/30/17 * * Date Last Modified: 11/30/17 * * Description: gets the possible combinations for die_values * Input parameters: int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6 * * Returns: int * Preconditions: * * Postconditions: None * *************************************************************/ int get_die_values_ai(int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6) { *ai1 = rand() % 6 + 1; *ai2 = rand() % 6 + 1; *ai3 = rand() % 6 + 1; *ai4 = rand() % 6 + 1; *ai5 = rand() % 6 + 1; *ai6 = rand() % 6 + 1; } /************************************************************* * Function: sort_die_value * * Date Created: 11/29/17 * * Date Last Modified: 11/29/17 * * Description: sorts the die values from least to greatest. * Input parameters: int *die1, int *die2, int *die3, int *die4, int *die5 p1 is the smallest number while *p5 is the greatest number * * Returns: * * Preconditions: * * Postconditions: None *PLEASE NOTE: I TOOK THE BUBBLE SORT CODE FROM http://www.programmingsimplified.com/c/source-code/c-program-bubble-sort. I DID NOT QUITE UNDERSTAND THE ONE THAT WAS GIVEN, SO I DECIDED TO LOOK ONLINE. *PLEASE NOTE: I TOOK THE BUBBLE SORT CODE FROM http://www.programmingsimplified.com/c/source-code/c-program-bubble-sort. I DID NOT QUITE UNDERSTAND THE ONE THAT WAS GIVEN, SO I DECIDED TO LOOK ONLINE. *PLEASE NOTE: I TOOK THE BUBBLE SORT CODE FROM http://www.programmingsimplified.com/c/source-code/c-program-bubble-sort. I DID NOT QUITE UNDERSTAND THE ONE THAT WAS GIVEN, SO I DECIDED TO LOOK ONLINE. *PLEASE NOTE: I TOOK THE BUBBLE SORT CODE FROM http://www.programmingsimplified.com/c/source-code/c-program-bubble-sort. I DID NOT QUITE UNDERSTAND THE ONE THAT WAS GIVEN, SO I DECIDED TO LOOK ONLINE. *PLEASE NOTE: I TOOK THE BUBBLE SORT CODE FROM http://www.programmingsimplified.com/c/source-code/c-program-bubble-sort. I DID NOT QUITE UNDERSTAND THE ONE THAT WAS GIVEN, SO I DECIDED TO LOOK ONLINE. *PLEASE NOTE: I TOOK THE BUBBLE SORT CODE FROM http://www.programmingsimplified.com/c/source-code/c-program-bubble-sort. I DID NOT QUITE UNDERSTAND THE ONE THAT WAS GIVEN, SO I DECIDED TO LOOK ONLINE. *PLEASE NOTE: I TOOK THE BUBBLE SORT CODE FROM http://www.programmingsimplified.com/c/source-code/c-program-bubble-sort. I DID NOT QUITE UNDERSTAND THE ONE THAT WAS GIVEN, SO I DECIDED TO LOOK ONLINE. *PLEASE NOTE: I TOOK THE BUBBLE SORT CODE FROM http://www.programmingsimplified.com/c/source-code/c-program-bubble-sort. I DID NOT QUITE UNDERSTAND THE ONE THAT WAS GIVEN, SO I DECIDED TO LOOK ONLINE. *************************************************************/ int sort_die_values(int *die1, int *die2, int *die3, int *die4, int *die5,int *die6, int *p1, int *p2, int *p3, int *p4, int *p5,int*p6) { int array[6] = {*die1,*die2,*die3,*die4,*die5,*die6 }, c, d, swap; /*for (c = 0; c < 5; c++) { for (d = 0; d < 5; d++) { if (array[d] > array[d + 1]) { swap = array[d]; array[d] = array[d + 1]; array[d + 1] = swap; } } }*/ for (c = 0; c < (6 -1); c++) { for (d = 0; d < 6 - c - 1; d++) { if (array[d] > array[d + 1]) /* For decreasing order use < */ { swap = array[d]; array[d] = array[d + 1]; array[d + 1] = swap; } } } /*printf("Sorted list in ascending order:\n"); for (c = 0; c < 5; c++) printf("%d\n", array[c]);*/ *p1 = array[0]; *p2 = array[1]; *p3 = array[2]; *p4 = array[3]; *p5 = array[4]; *p6 = array[5]; /*printf("\n"); printf("%d\n", *p1); printf("%d\n", *p2); printf("%d\n", *p3); printf("%d\n", *p4); printf("%d\n", *p5);*/ return 0; } /************************************************************* * Function: sort_die_values_ai * * Date Created: 11/30/17 * * Date Last Modified: 11/30/17 * * Description: sorts the die values from least to greatest. * Input parameters: int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6 * * Returns: int * * Preconditions: * * Postconditions: None *PLEASE NOTE: I TOOK THE BUBBLE SORT CODE FROM http://www.programmingsimplified.com/c/source-code/c-program-bubble-sort. I DID NOT QUITE UNDERSTAND THE ONE THAT WAS GIVEN, SO I DECIDED TO LOOK ONLINE. *PLEASE NOTE: I TOOK THE BUBBLE SORT CODE FROM http://www.programmingsimplified.com/c/source-code/c-program-bubble-sort. I DID NOT QUITE UNDERSTAND THE ONE THAT WAS GIVEN, SO I DECIDED TO LOOK ONLINE. *PLEASE NOTE: I TOOK THE BUBBLE SORT CODE FROM http://www.programmingsimplified.com/c/source-code/c-program-bubble-sort. I DID NOT QUITE UNDERSTAND THE ONE THAT WAS GIVEN, SO I DECIDED TO LOOK ONLINE. *PLEASE NOTE: I TOOK THE BUBBLE SORT CODE FROM http://www.programmingsimplified.com/c/source-code/c-program-bubble-sort. I DID NOT QUITE UNDERSTAND THE ONE THAT WAS GIVEN, SO I DECIDED TO LOOK ONLINE. *PLEASE NOTE: I TOOK THE BUBBLE SORT CODE FROM http://www.programmingsimplified.com/c/source-code/c-program-bubble-sort. I DID NOT QUITE UNDERSTAND THE ONE THAT WAS GIVEN, SO I DECIDED TO LOOK ONLINE. *PLEASE NOTE: I TOOK THE BUBBLE SORT CODE FROM http://www.programmingsimplified.com/c/source-code/c-program-bubble-sort. I DID NOT QUITE UNDERSTAND THE ONE THAT WAS GIVEN, SO I DECIDED TO LOOK ONLINE. *PLEASE NOTE: I TOOK THE BUBBLE SORT CODE FROM http://www.programmingsimplified.com/c/source-code/c-program-bubble-sort. I DID NOT QUITE UNDERSTAND THE ONE THAT WAS GIVEN, SO I DECIDED TO LOOK ONLINE. *PLEASE NOTE: I TOOK THE BUBBLE SORT CODE FROM http://www.programmingsimplified.com/c/source-code/c-program-bubble-sort. I DID NOT QUITE UNDERSTAND THE ONE THAT WAS GIVEN, SO I DECIDED TO LOOK ONLINE. *************************************************************/ int sort_die_values_ai(int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6) { int array[6] = { *ai1,*ai2,*ai3,*ai4,*ai5,*ai6 }, c, d, swap; for (c = 0; c < (6 - 1); c++) { for (d = 0; d < 6 - c - 1; d++) { if (array[d] > array[d + 1]) /* For decreasing order use < */ { swap = array[d]; array[d] = array[d + 1]; array[d + 1] = swap; } } } *ai1 = array[0]; *ai2 = array[1]; *ai3 = array[2]; *ai4 = array[3]; *ai5 = array[4]; *ai6 = array[5]; } /************************************************************* * Function: sum_of_ones * * Date Created: 11/29/17 * * Date Last Modified: 11/29/17 * * Description: gets the combinations of ones * Input parameters: int *p1, int *p2, int *p3, int *p4, int *p5, int *p6 * * Returns: ones * * Preconditions: * * Postconditions: None * *************************************************************/ int sum_of_ones(int *p1, int *p2, int *p3, int *p4, int *p5, int *p6) { int ones=0; if (*p1 == 1) { ones++; } if (*p2 == 1) { ones++; } if (*p3 == 1) { ones++; } if (*p4 == 1) { ones++; } if (*p5 == 1) { ones++; } if (*p6 == 1) { ones++; } //printf("%d\n", ones); return ones; } /************************************************************* * Function: sum_of_ones_ai * * Date Created: 12/1/17 * * Date Last Modified: 12/1/17 * * Description: gets the combinations of ones * Input parameters: int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6 * * Returns: ai ones * * Preconditions: * * Postconditions: None * *************************************************************/ int sum_of_ones_ai(int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6) { int ai_ones = 0; if (*ai1 == 1) { ai_ones++; } if (*ai2 == 1) { ai_ones++; } if (*ai3 == 1) { ai_ones++; } if (*ai4 == 1) { ai_ones++; } if (*ai5 == 1) { ai_ones++; } if (*ai6 == 1) { ai_ones++; } return ai_ones; } /************************************************************* * Function: sum_of_twos * * Date Created: 11/29/17 * * Date Last Modified: 11/29/17 * * Description: adds the twos * Input parameters: int *p1, int *p2, int *p3, int *p4, int *p5, int *p6 * * Returns: twos * * Preconditions: * * Postconditions: None * *************************************************************/ int sum_of_twos(int *p1, int *p2, int *p3, int *p4, int *p5,int *p6) { int twos = 0; if (*p1 == 2) { twos=twos+2; } if (*p2 == 2) { twos = twos + 2; } if (*p3 == 2) { twos = twos + 2; } if (*p4 == 2) { twos = twos + 2; } if (*p5 == 2) { twos = twos + 2; } if (*p6 == 2) { twos = twos + 2; } //printf("%d\n", twos); return twos; } /************************************************************* * Function: sum_of_twos_ai * * Date Created: 12/1/17 * * Date Last Modified: 12/1/17 * * Description: adds the twos * Input parameters: int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6 * * Returns: twos * * Preconditions: * * Postconditions: None * *************************************************************/ int sum_of_twos_ai(int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6) { int ai_twos = 0; if (*ai1 == 2) { ai_twos = ai_twos + 2; } if (*ai2 == 2) { ai_twos = ai_twos + 2; } if (ai3 == 2) { ai_twos = ai_twos + 2; } if (*ai4 == 2) { ai_twos = ai_twos + 2; } if (*ai5 == 2) { ai_twos = ai_twos + 2; } if (*ai6 == 2) { ai_twos = ai_twos + 2; } //printf("%d\n", twos); return ai_twos; } /************************************************************* * Function: sum_of_threes * * Date Created: 11/29/17 * * Date Last Modified: 11/29/17 * * Description: adds the threes * Input parameters: int *p1, int *p2, int *p3, int *p4, int *p5,int *p6 * * Returns: threes * * Preconditions: * * Postconditions: None * *************************************************************/ int sum_of_threes(int *p1, int *p2, int *p3, int *p4, int *p5,int *p6) { int threes = 0; if (*p1 == 3) { threes = threes + 3; } if (*p2 == 3) { threes = threes + 3; } if (*p3 == 3) { threes = threes + 3; } if (*p4 == 3) { threes = threes + 3; } if (*p5 == 3) { threes = threes + 3; } if (*p6 == 3) { threes = threes + 3; } //printf("%d\n", threes); return threes; } /************************************************************* * Function: sum_of_threes_ai * * Date Created : 12 / 1 / 17 * * Date Last Modified : 12 / 1 / 17 * * Description : adds the threes * Input parameters : int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6 * * Returns : threes * * Preconditions : * * Postconditions : None * *************************************************************/ int sum_of_threes_ai(int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6) { int ai_threes = 0; if (*ai1 == 3) { ai_threes = ai_threes + 3; } if (*ai2 == 3) { ai_threes = ai_threes + 3; } if (*ai3 == 3) { ai_threes = ai_threes + 3; } if (*ai4 == 3) { ai_threes = ai_threes + 3; } if (*ai5 == 3) { ai_threes = ai_threes + 3; } if (*ai6 == 3) { ai_threes = ai_threes + 3; } //printf("%d\n", threes); return ai_threes; } /************************************************************* * Function: sum_of_fours * * Date Created: 11/29/17 * * Date Last Modified: 11/29/17 * * Description: adds the fours * Input parameters: int *p1, int *p2, int *p3, int *p4, int *p5,int *p6 * * Returns: fours * * Preconditions: * * Postconditions: None * *************************************************************/ int sum_of_fours(int *p1, int *p2, int *p3, int *p4, int *p5,int *p6) { int fours = 0; if (*p1 == 4) { fours = fours + 4; } if (*p2 == 4) { fours = fours + 4; } if (*p3 == 4) { fours = fours + 4; } if (*p4 == 4) { fours = fours + 4; } if (*p5 == 4) { fours = fours + 4; } if (*p6 == 4) { fours = fours + 4; } //printf("%d\n", fours); return fours; } /************************************************************* * Function: sum_of_fours_ai * * Date Created: 12/1/17 * * Date Last Modified: 12/1/17 * * Description: adds the fours * Input parameters: int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6 * * Returns: fours * * Preconditions: * * Postconditions: None * *************************************************************/ int sum_of_fours_ai(int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6) { int ai_fours = 0; if (*ai1 == 4) { ai_fours = ai_fours + 4; } if (*ai2 == 4) { ai_fours = ai_fours + 4; } if (*ai3 == 4) { ai_fours = ai_fours + 4; } if (*ai4 == 4) { ai_fours = ai_fours + 4; } if (*ai5 == 4) { ai_fours = ai_fours + 4; } if (*ai6 == 4) { ai_fours = ai_fours + 4; } //printf("%d\n", fours); return ai_fours; } /************************************************************* * Function: sum_of_fives * * Date Created: 11/29/17 * * Date Last Modified: 11/29/17 * * Description: adds the fives * Input parameters: int *p1, int *p2, int *p3, int *p4, int *p5,int *p6 * * Returns: fives * * Preconditions: * * Postconditions: None * *************************************************************/ int sum_of_fives(int *p1, int *p2, int *p3, int *p4, int *p5,int *p6) { int fives = 0; if (*p1 == 5) { fives = fives + 5; } if (*p2 == 5) { fives = fives + 5; } if (*p3 == 5) { fives = fives + 5; } if (*p4 == 5) { fives = fives + 5; } if (*p5 == 5) { fives = fives + 5; } if (*p6 == 5) { fives = fives + 5; } //printf("%d\n", fives); return fives; } /************************************************************* * Function: sum_of_fives_ai * * Date Created: 12/1/17 * * Date Last Modified: 12/1/17 * * Description: adds the fives * Input parameters: int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6 * * Returns: fives * * Preconditions: * * Postconditions: None * *************************************************************/ int sum_of_fives_ai(int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6) { int ai_fives = 0; if (*ai1 == 5) { ai_fives = ai_fives + 5; } if (*ai2 == 5) { ai_fives = ai_fives + 5; } if (*ai3 == 5) { ai_fives = ai_fives + 5; } if (*ai4 == 5) { ai_fives = ai_fives + 5; } if (*ai5 == 5) { ai_fives = ai_fives + 5; } if (*ai6 == 5) { ai_fives = ai_fives + 5; } //printf("%d\n", fives); return ai_fives; } /************************************************************* * Function: sum_of_sixes * * Date Created: 11/29/17 * * Date Last Modified: 11/29/17 * * Description: adds the sixes * Input parameters: int *p1, int *p2, int *p3, int *p4, int *p5,int *p6 * * Returns: sixes * * Preconditions: * * Postconditions: None * *************************************************************/ int sum_of_sixes(int *p1, int *p2, int *p3, int *p4, int *p5,int *p6) { int sixes = 0; if (*p1 == 6) { sixes = sixes + 6; } if (*p2 == 6) { sixes = sixes + 6; } if (*p3 == 6) { sixes = sixes + 6; } if (*p4 == 6) { sixes = sixes + 6; } if (*p5 == 6) { sixes = sixes + 6; } if (*p6 == 6) { sixes = sixes + 6; } //printf("%d\n", sixes); return sixes; } /************************************************************* * Function: sum_of_sixes_ai * * Date Created: 12/1/17 * * Date Last Modified: 12/1/17 * * Description: adds the sixes * Input parameters: int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6 * * Returns: sixes * * Preconditions: * * Postconditions: None * *************************************************************/ int sum_of_sixes_ai(int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6) { int ai_sixes = 0; if (*ai1 == 6) { ai_sixes = ai_sixes + 6; } if (*ai2 == 6) { ai_sixes = ai_sixes + 6; } if (*ai3 == 6) { ai_sixes = ai_sixes + 6; } if (*ai4 == 6) { ai_sixes = ai_sixes + 6; } if (*ai5 == 6) { ai_sixes = ai_sixes + 6; } if (*ai6 == 6) { ai_sixes = ai_sixes + 6; } //printf("%d\n", sixes); return ai_sixes; } /************************************************************* * Function: three of a kind * * Date Created : 11 / 29 / 17 * * Date Last Modified : 11 / 29 / 17 * * Description : finds if there is 3 of the same number * Input parameters : int *p1, int *p2, int *p3, int *p4, int *p5, int *p6 * * Returns : three of a kind * * Preconditions : * * Postconditions : None * *************************************************************/ int three_of_a_kind(int *p1, int *p2, int *p3, int *p4, int *p5, int *p6) { int th_kind = 0; if (*p1 == *p2&&*p1 == *p3) { th_kind++; } if (*p2 == *p3&&*p2 == *p4) { th_kind++; } if (*p3 == *p4&&*p3 == *p5) { th_kind++; } if (*p4 == *p5&&*p4 == *p6) { th_kind++; } if (th_kind > 0) { th_kind = *p1 + *p2 + *p3 + *p4 + *p5+*p6; } //printf("%d\n", th_kind); return th_kind; } /************************************************************* * Function: three of a kind ai * * Date Created : 12 / 1 / 17 * * Date Last Modified : 12 /1 / 17 * * Description : finds if there is 3 of the same number * Input parameters : int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6 * * Returns : three of a kind ai * * Preconditions : * * Postconditions : None * *************************************************************/ int three_of_a_kind_ai(int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6) { int ai_th_kind = 0; if (*ai1 == *ai2&&*ai1 == *ai3) { ai_th_kind++; } if (*ai2 == *ai3&&*ai2 == *ai4) { ai_th_kind++; } if (*ai3 == *ai4&&*ai3 == *ai5) { ai_th_kind++; } if (*ai4 == *ai5&&*ai4 == *ai6) { ai_th_kind++; } if (ai_th_kind > 0) { ai_th_kind = *ai1 + *ai2 + *ai3 + *ai4 + *ai5 + *ai6; } //printf("%d\n", th_kind); return ai_th_kind; } /************************************************************* * Function: four of a kind * * Date Created : 11 / 29 / 17 * * Date Last Modified : 11 / 29 / 17 * * Description : finds if there is 4 of the same number * Input parameters : int *p1, int *p2, int *p3, int *p4, int *p5, int *p6 * * Returns : four of a kind * * Preconditions : * * Postconditions : None * *************************************************************/ int four_of_a_kind(int *p1, int *p2, int *p3, int *p4, int *p5, int *p6) { int fo_kind = 0; if (*p1 == *p2&&*p1 == *p3&&*p1==*p4) { fo_kind++; } if (*p2 == *p3&&*p2 == *p4&&*p2==*p5) { fo_kind++; } if (*p3 == *p4&&*p3 == *p5&&*p3 == *p6) { fo_kind++; } if (fo_kind > 0) { fo_kind= *p1 + *p2 + *p3 + *p4 + *p5 + *p6; } //printf("%d\n", fo_kind); return fo_kind; } /************************************************************* * Function: four of a kind ai * * Date Created : 12 /1 / 17 * * Date Last Modified : 12 / 1 / 17 * * Description : finds if there is 4 of the same number * Input parameters : iint *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6 * * Returns : four of a kind ai * * Preconditions : * * Postconditions : None * *************************************************************/ int four_of_a_kind_ai(int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6) { int ai_fo_kind = 0; if (*ai1 == *ai2&&*ai1 == *ai3&&*ai1 == *ai4) { ai_fo_kind++; } if (*ai2 == *ai3&&*ai2 == *ai4&&*ai2 == *ai5) { ai_fo_kind++; } if (*ai3 == *ai4&&*ai3 == *ai5&&*ai3 == *ai6) { ai_fo_kind++; } if (ai_fo_kind > 0) { ai_fo_kind = *ai1 + *ai2 + *ai3 + *ai4 + *ai5 + *ai6; } //printf("%d\n", fo_kind); return ai_fo_kind; } /************************************************************* * Function: full_house * * Date Created : 11 / 29 / 17 * * Date Last Modified : 11 / 29 / 17 * * Description : finds if there is One pair and a three-of-a-kind * Input parameters : int *p1, int *p2, int *p3, int *p4, int *p5, int *p6 * * Returns : fu_house * * Preconditions : * * Postconditions : None * *************************************************************/ int full_house(int *p1, int *p2, int *p3, int *p4, int *p5, int *p6) { int fu_house = 0; int th_kind = 0; int pairs = 0; int total = 0; if (*p1 == *p2&&*p1 == *p3) { th_kind++; } if (*p2 == *p3&&*p2 == *p4) { th_kind++; } if (*p3 == *p4&&*p3 == *p5) { th_kind++; } if (*p4 == *p5&&*p4 == *p6) { th_kind++; } if (*p1 == *p2) { pairs=pairs+3; } if (*p2 == *p3) { pairs = pairs + 3; } if (*p3 == *p4) { pairs = pairs + 3; } if (*p5 == *p6) { pairs = pairs + 3; } total = pairs + th_kind; if (total > 4) { total = 25; } else { total = 0; } //printf("%d\n", total); fu_house = total; return fu_house; } /************************************************************* * Function: full_house_ai * * Date Created : 12 / 1 / 17 * * Date Last Modified : 12 / 1 / 17 * * Description : finds if there is One pair and a three-of-a-kind * Input parameters : int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6 * * Returns : ai_fu_house * * Preconditions : * * Postconditions : None * *************************************************************/ int full_house_ai(int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6) { int ai_fu_house = 0; int ai_th_kind = 0; int ai_pairs = 0; int ai_total = 0; if (*ai1 == *ai2&&*ai1 == *ai3) { ai_th_kind++; } if (*ai2 == *ai3&&*ai2 == *ai4) { ai_th_kind++; } if (*ai3 == *ai4&&*ai3 == *ai5) { ai_th_kind++; } if (*ai4 == *ai5&&*ai4 == *ai6) { ai_th_kind++; } if (*ai1 == *ai2) { ai_pairs = ai_pairs + 3; } if (*ai2 == *ai3) { ai_pairs = ai_pairs + 3; } if (*ai3 == *ai4) { ai_pairs = ai_pairs + 3; } if (*ai5 == *ai6) { ai_pairs = ai_pairs + 3; } ai_total = ai_pairs + ai_th_kind; if (ai_total > 4) { ai_total = 25; } else { ai_total = 0; } //printf("%d\n", total); ai_fu_house = ai_total; return ai_fu_house; } /************************************************************* * Function: small_straight * * Date Created : 11 / 29 / 17 * * Date Last Modified : 11 / 29 / 17 * * Description : A sequence of four dice * Input parameters : int *p1, int *p2, int *p3, int *p4, int *p5, int *p6 * * Returns : sma_straight * * Preconditions : * * Postconditions : None * *************************************************************/ int small_straight(int *p1, int *p2, int *p3, int *p4, int *p5, int *p6) { int sma_straight = 0; if (*p1 < *p2&&*p2 < *p3&&*p3 < *p4) { sma_straight = 30; } if (*p2 < *p3&&*p3 < *p4&&*p4 < *p5) { sma_straight = 30; } if (*p3 < *p4&&*p4 < *p5&&*p5 < *p6) { sma_straight = 30; } //printf("%d\n", sma_straight); return sma_straight; } /************************************************************* * Function: small_straight_ai * * Date Created : 12 / 1 / 17 * * Date Last Modified : 12 / 1 / 17 * * Description : A sequence of four dice * Input parameters : int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6 * * Returns : sma_straight_ai * * Preconditions : * * Postconditions : None * *************************************************************/ int small_straight_ai(int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6) { int ai_sma_straight = 0; if (*ai1 < *ai2&&*ai2 < *ai3&&*ai3 < *ai4) { ai_sma_straight = 30; } if (*ai2 < *ai3&&*ai3 < *ai4&&*ai4 < *ai5) { ai_sma_straight = 30; } if (*ai3 < *ai4&&*ai4 < *ai5&&*ai5 < *ai6) { ai_sma_straight = 30; } //printf("%d\n", sma_straight); return ai_sma_straight; } /************************************************************* * Function: large_straight * * Date Created : 11 / 29 / 17 * * Date Last Modified : 11 / 29 / 17 * * Description : A sequence of five dice * Input parameters : int *p1, int *p2, int *p3, int *p4, int *p5, int *p6 * * Returns : lar_straight * * Preconditions : * * Postconditions : None * *************************************************************/ int large_straight(int *p1, int *p2, int *p3, int *p4, int *p5, int *p6) { int lar_straight = 0; if (*p1 < *p2&&*p2 < *p3&&*p3 < *p4&&*p4<*p5) { lar_straight = 40; } if (*p2 < *p3&&*p3 < *p4&&*p4 < *p5&&*p5<*p6) { lar_straight = 40; } //printf("%d\n", lar_straight); return lar_straight; } /************************************************************* * Function: large_straight_ai * * Date Created : 12 / 1 / 17 * * Date Last Modified : 12 / 1 / 17 * * Description : A sequence of five dice * Input parameters : int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6 * * Returns : ai_lar_straight * * Preconditions : * * Postconditions : None * *************************************************************/ int large_straight_ai(int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6) { int ai_lar_straight = 0; if (*ai1 < *ai2&&*ai2 < *ai3&&*ai3 < *ai4&&*ai4<*ai5) { ai_lar_straight = 40; } if (*ai2 < *ai3&&*ai3 < *ai4&&*ai4 < *ai5&&*ai5<*ai6) { ai_lar_straight = 40; } //printf("%d\n", lar_straight); return ai_lar_straight; } /************************************************************* * Function: yahtzee * * Date Created : 11 / 29 / 17 * * Date Last Modified : 11 / 29 / 17 * * Description : Five dice with the same face * Input parameters : int *p1, int *p2, int *p3, int *p4, int *p5, int *p6 * * Returns : yahtzee * * Preconditions : * * Postconditions : None * *************************************************************/ int yahtzee(int *p1, int *p2, int *p3, int *p4, int *p5, int *p6) { int yahtzee1 = 0; if (*p1 == *p2 == *p3 == *p4 == *p5 == *p6) { yahtzee1 = 50; } //printf("%d\n", yahtzee1); return yahtzee1; } /************************************************************* * Function: yahtzee_ai * * Date Created : 12 / 1 / 17 * * Date Last Modified : 12 / 1 / 17 * * Description : Five dice with the same face * Input parameters : int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6 * * Returns : ai_yahtzee * * Preconditions : * * Postconditions : None * *************************************************************/ int yahtzee_ai(int *ai1, int *ai2, int *ai3, int *ai4, int *ai5, int *ai6) { int ai_yahtzee1 = 0; if (*ai1 == *ai2 == *ai3 == *ai4 == *ai5 == *ai6) { ai_yahtzee1 = 50; } //printf("%d\n", yahtzee1); return ai_yahtzee1; } /************************************************************* * Function: chance * * Date Created : 11 / 29 / 17 * * Date Last Modified : 11 / 29 / 17 * * Description : May be used for any sequence of dice; this is the catch all combination * Input parameters : int *p1, int *p2, int *p3, int *p4, int *p5, int *p6 * * Returns : chan * * Preconditions : * * Postconditions : None * *************************************************************/ int chance(int ones, int twos, int threes, int fours, int fives, int sixes,int th_kind, int fo_kind, int fu_house, int sma_straight, int lar_straight, int yahtzee1) { int chan = 0; if (ones>0&&twos>0&&threes>0&&fours>0&&fives>0&&sixes>0&&th_kind > 0 && fo_kind > 0 && fu_house > 0 && sma_straight > 0 && lar_straight > 0 && yahtzee1 > 0) { chan = th_kind; } return chan; } /************************************************************* * Function: chance_ai * * Date Created : 11 / 29 / 17 * * Date Last Modified : 11 / 29 / 17 * * Description : May be used for any sequence of dice; this is the catch all combination * Input parameters : int *p1, int *p2, int *p3, int *p4, int *p5, int *p6 * * Returns : chan * * Preconditions : * * Postconditions : None * *************************************************************/ int chance_ai(int ai_ones, int ai_twos, int ai_threes, int ai_fours, int ai_fives, int ai_sixes, int ai_th_kind, int ai_fo_kind, int ai_fu_house, int ai_sma_straight, int ai_lar_straight, int ai_yahtzee1) { int ai_chan = 0; if (ai_ones>0&&ai_twos>0&&ai_threes>0&&ai_fours>0&&ai_fives>0&&ai_sixes>0&&ai_th_kind > 0 && ai_fo_kind > 0 && ai_fu_house > 0 && ai_sma_straight > 0 && ai_lar_straight > 0 && ai_yahtzee1 > 0) { ai_chan = ai_th_kind; } return ai_chan; }
C
#include <pal.h> /** * * Calculates the inverse hyperbolic cosine of 'a'. Input values must be > 1. * The function does not check for illegal input values. * * @param a Pointer to input vector * * @param c Pointer to output vector * * @param n Size of 'a' and 'c' vector. * * @param p Number of processor to use (task parallelism) * * @param team Team to work with * * @return None * */ #include <math.h> void p_acosh_f32(const float *a, float *c, int n, int p, p_team_t team) { int i; for (i = 0; i < n; i++) { *(c + i) = acoshf(*(a + i)); } }
C
#include <stdio.h> #include<stdlib.h> int main(){ //calloc stands for CONTINUOUS ALLOCATION It initialize each memory nlock with a default value of 0 //syntax => (float *)calloc(30,sizeof(float)); //calloc(30,sizeof(float)) => allocates continous space in memory for 30 blocks(float) // if the space is not sufficient memory allocation falis and a NULL pointer returns int *ptr; ptr = (int *)calloc(6,sizeof(int)); //it makes 6 blocks for int with default value 0 int i; for(i=0;i<6;i++){ printf("Enter the number \n"); scanf("%d",&ptr[i]); } for(i=0;i<6;i++){ printf("The element are %d\n",ptr[i]); } return 0; }
C
#include "vogle.h" #ifdef TC extern double cos(); extern double sin(); extern double asin(); extern double sqrt(); #else #include <math.h> #endif /* * NOTE: the words hither and yon are used in this file instead of near and far * as they are keywords on some PC compilers (groan). Change them back at your * on peril. */ #define SQ(a) ((a)*(a)) #define COT(a) ((float)(cos((double)(a)) / sin((double)(a)))) /* * polarview * * Specify the viewer's position in polar coordinates by giving * the distance from the viewpoint to the world origin, * the azimuthal angle in the x-y plane, measured from the y-axis, * the incidence angle in the y-z plane, measured from the z-axis, * and the twist angle about the line of sight. * */ void polarview(dist, azim, inc, twist) float dist, azim, inc, twist; { if (!vdevice.initialised) verror("polarview: vogle not initialised"); translate(0.0, 0.0, -dist); rotate(-twist, 'z'); rotate(-inc, 'x'); rotate(-azim, 'z'); } /* * up * * set the up vector */ up(x, y, z) float x, y, z; { vdevice.upset = 1; vdevice.upvector[V_X] = x; vdevice.upvector[V_Y] = y; vdevice.upvector[V_Z] = z; } /* * normallookat * * do the standard lookat transformation. */ static void normallookat(vx, vy, vz, px, py, pz) float vx, vy, vz, px, py, pz; { float l2, l3, sintheta, sinphi, costheta, cosphi; Matrix tmp; l2 = sqrt((double)(SQ((px - vx)) + SQ((pz - vz)))); l3 = sqrt((double)(SQ((px - vx)) + SQ((py - vy)) + SQ((pz - vz)))); if (l3 != 0.0) { sinphi = (vy - py) / l3; cosphi = l2 / l3; /* * Rotate about X by phi */ identmatrix(tmp); tmp[1][1] = tmp[2][2] = cosphi; tmp[1][2] = sinphi; tmp[2][1] = -sinphi; multmatrix(tmp); } if (l2 != 0.0) { sintheta = (px - vx) / l2; costheta = (vz - pz) / l2; /* * Rotate about Y by theta */ identmatrix(tmp); tmp[0][0] = tmp[2][2] = costheta; tmp[0][2] = -sintheta; tmp[2][0] = sintheta; multmatrix(tmp); } } /* * lookatwithup * * do the standard lookat transformation using an up vector as well. */ static void lookatwithup(vx, vy, vz, px, py, pz) float vx, vy, vz, px, py, pz; { Vector t, u, s; Matrix tmp; double dy, dz, lt, lu; t[V_X] = vx - px; t[V_Y] = vy - py; t[V_Z] = vz - pz; u[V_X] = vdevice.upvector[V_X]; u[V_Y] = vdevice.upvector[V_Y]; u[V_Z] = vdevice.upvector[V_Z]; lt = sqrt(t[V_X] * t[V_X] + t[V_Y] * t[V_Y] + t[V_Z] * t[V_Z]); if (lt == 0.0) verror("vogle: can't have eyepoint and reference point the same in lookat.\n"); lu = sqrt(u[V_X] * u[V_X] + u[V_Y] * u[V_Y] + u[V_Z] * u[V_Z]); if (lu == 0.0) verror("vogle: invalid up vector in lookat.\n"); /* * normalise t and u */ t[V_X] /= lt; t[V_Y] /= lt; t[V_Z] /= lt; u[V_X] /= lu; u[V_Y] /= lu; u[V_Z] /= lu; dz = t[V_X] * u[V_X] + t[V_Y] * u[V_Y] + t[V_Z] * u[V_Z]; if (fabs(dz) >= 1.0) verror("vogle: up vector and direction of view are the same.\n"); dy = sqrt(1.0 - dz * dz); /* * calculate view up */ u[V_X] = (u[V_X] - dz * t[V_X]) / dy; u[V_Y] = (u[V_Y] - dz * t[V_Y]) / dy; u[V_Z] = (u[V_Z] - dz * t[V_Z]) / dy; /* * calculate side vector (cross product of u and t) */ s[V_X] = u[V_Y] * t[V_Z] - u[V_Z] * t[V_Y]; s[V_Y] = u[V_Z] * t[V_X] - u[V_X] * t[V_Z]; s[V_Z] = u[V_X] * t[V_Y] - u[V_Y] * t[V_X]; identmatrix(tmp); tmp[0][0] = s[V_X]; tmp[1][0] = s[V_Y]; tmp[2][0] = s[V_Z]; tmp[0][1] = u[V_X]; tmp[1][1] = u[V_Y]; tmp[2][1] = u[V_Z]; tmp[0][2] = t[V_X]; tmp[1][2] = t[V_Y]; tmp[2][2] = t[V_Z]; multmatrix(tmp); } /* * lookat * * Specify the viewer's position by giving a viewpoint and a * reference point in world coordinates. A twist about the line * of sight may also be given. */ void lookat(vx, vy, vz, px, py, pz, twist) float vx, vy, vz, px, py, pz, twist; { if (!vdevice.initialised) verror("lookat: vogle not initialised"); rotate(-twist, 'z'); if (vdevice.upset) lookatwithup(vx, vy, vz, px, py, pz); else normallookat(vx, vy, vz, px, py, pz); translate(-vx, -vy, -vz); } /* * perspective * * Specify a perspective viewing pyramid in world coordinates by * giving a field of view, aspect ratio, and the locations of the * near(hither) and far(yon) clipping planes in the z direction. */ void perspective(fov, aspect, hither, yon) float fov, aspect, hither, yon; { Matrix mat; if (!vdevice.initialised) verror("perspective: vogle not initialised"); if (aspect == 0.0) verror("perspective: can't have zero aspect ratio!"); if ((yon - hither) == 0.0) verror("perspective: near clipping plane same as far one."); if (fov == 0.0 || fov == 180.0) verror("perspective: bad field of view passed."); identmatrix(mat); mat[0][0] = COT((D2R * fov / 2.0)) / aspect; mat[1][1] = COT((D2R * fov / 2.0)); mat[2][2] = -(yon + hither) / (yon - hither); mat[2][3] = -1; mat[3][2] = -2.0 * yon * hither / (yon - hither); mat[3][3] = 0; loadmatrix(mat); } /* * window * * Specify a perspective viewing pyramid in world coordinates by * giving a rectangle at the near clipping plane and the location * of the far clipping plane. * */ void window(left, right, bottom, top, hither, yon) float left, right, bottom, top, hither, yon; { Matrix mat; if (!vdevice.initialised) verror("window: vogle not initialised"); if ((right - left) == 0.0) verror("window: left clipping plane same as right one."); if ((top - bottom) == 0.0) verror("window: bottom clipping plane same as top one."); if ((yon - hither) == 0.0) verror("window: near clipping plane same as far one."); identmatrix(mat); mat[0][0] = 2.0 * hither / (right - left); mat[1][1] = 2.0 * hither / (top - bottom); mat[2][0] = (right + left) / (right - left); mat[2][1] = (top + bottom) / (top - bottom); mat[2][2] = -(yon + hither) / (yon - hither); mat[2][3] = -1.0; mat[3][2] = -2.0 * yon * hither / (yon - hither); mat[3][3] = 0.0; loadmatrix(mat); } /* * ortho * * Define a three dimensional viewing box by giving the left, * right, bottom and top clipping plane locations and the distances * along the line of sight to the near and far clipping planes. * */ void ortho(left, right, bottom, top, hither, yon) float left, right, bottom, top, hither, yon; { Matrix mat; if (!vdevice.initialised) verror("ortho: vogle not initialised"); if ((right - left) == 0.0) verror("ortho: left clipping plane same as right one."); if ((top - bottom) == 0.0) verror("ortho: bottom clipping plane same as top one."); if ((yon - hither) == 0.0) verror("ortho: near clipping plane same as far one."); identmatrix(mat); mat[0][0] = 2.0 / (right - left); mat[1][1] = 2.0 / (top - bottom); mat[2][2] = -2.0 / (yon - hither); mat[3][0] = -(right + left) / (right - left); mat[3][1] = -(top + bottom) / (top - bottom); mat[3][2] = -(yon + hither) / (yon - hither); loadmatrix(mat); } /* * ortho2 * * Specify a two dimensional viewing rectangle. * */ void ortho2(left, right, bottom, top) float left, right, bottom, top; { Matrix mat; if (!vdevice.initialised) verror("ortho2: vogle not initialised"); identmatrix(mat); if ((right - left) == 0.0) verror("ortho2: left clipping plane same as right one."); if ((top - bottom) == 0.0) verror("ortho2: bottom clipping plane same as top one."); mat[0][0] = 2.0 / (right - left); mat[1][1] = 2.0 / (top - bottom); mat[2][2] = -1.0; mat[3][0] = -(right + left) / (right - left); mat[3][1] = -(top + bottom) / (top - bottom); loadmatrix(mat); }
C
#include "libc/assert.h" #include "third_party/chibicc/chibicc.h" /* TODO(jart): Why can't these be const? */ Type ty_void[1] = {{TY_VOID, 1, 1}}; Type ty_bool[1] = {{TY_BOOL, 1, 1}}; Type ty_char[1] = {{TY_CHAR, 1, 1}}; Type ty_short[1] = {{TY_SHORT, 2, 2}}; Type ty_int[1] = {{TY_INT, 4, 4}}; Type ty_long[1] = {{TY_LONG, 8, 8}}; Type ty_int128[1] = {{TY_INT128, 16, 16}}; Type ty_uchar[1] = {{TY_CHAR, 1, 1, true}}; Type ty_ushort[1] = {{TY_SHORT, 2, 2, true}}; Type ty_uint[1] = {{TY_INT, 4, 4, true}}; Type ty_ulong[1] = {{TY_LONG, 8, 8, true}}; Type ty_uint128[1] = {{TY_INT128, 16, 16, true}}; Type ty_float[1] = {{TY_FLOAT, 4, 4}}; Type ty_double[1] = {{TY_DOUBLE, 8, 8}}; Type ty_ldouble[1] = {{TY_LDOUBLE, 16, 16}}; static Type *new_type(TypeKind kind, int size, int align) { Type *ty = alloc_type(); ty->kind = kind; ty->size = size; ty->align = align; return ty; } bool is_integer(Type *ty) { TypeKind k = ty->kind; return k == TY_BOOL || k == TY_CHAR || k == TY_SHORT || k == TY_INT || k == TY_LONG || k == TY_INT128 || k == TY_ENUM; } bool is_flonum(Type *ty) { return ty->kind == TY_FLOAT || ty->kind == TY_DOUBLE || ty->kind == TY_LDOUBLE; } bool is_numeric(Type *ty) { return is_integer(ty) || is_flonum(ty); } bool is_compatible(Type *t1, Type *t2) { if (t1 == t2) return true; if (t1->origin) return is_compatible(t1->origin, t2); if (t2->origin) return is_compatible(t1, t2->origin); if (t1->kind != t2->kind) return false; switch (t1->kind) { case TY_CHAR: case TY_SHORT: case TY_INT: case TY_LONG: case TY_INT128: return t1->is_unsigned == t2->is_unsigned; case TY_FLOAT: case TY_DOUBLE: case TY_LDOUBLE: return true; case TY_PTR: return is_compatible(t1->base, t2->base); case TY_FUNC: { if (!is_compatible(t1->return_ty, t2->return_ty)) return false; if (t1->is_variadic != t2->is_variadic) return false; Type *p1 = t1->params; Type *p2 = t2->params; for (; p1 && p2; p1 = p1->next, p2 = p2->next) { if (!is_compatible(p1, p2)) return false; } return p1 == NULL && p2 == NULL; } case TY_ARRAY: if (!is_compatible(t1->base, t2->base)) return false; return t1->array_len < 0 && t2->array_len < 0 && t1->array_len == t2->array_len; } return false; } Type *copy_type(Type *ty) { Type *ret = alloc_type(); *ret = *ty; ret->origin = ty; return ret; } Type *pointer_to(Type *base) { Type *ty = new_type(TY_PTR, 8, 8); ty->base = base; ty->is_unsigned = true; return ty; } Type *func_type(Type *return_ty) { // The C spec disallows sizeof(<function type>), but // GCC allows that and the expression is evaluated to 1. Type *ty = new_type(TY_FUNC, 1, 1); ty->return_ty = return_ty; return ty; } Type *array_of(Type *base, int len) { Type *ty = new_type(TY_ARRAY, base->size * len, base->align); ty->base = base; ty->array_len = len; return ty; } Type *vla_of(Type *base, Node *len) { Type *ty = new_type(TY_VLA, 8, 8); ty->base = base; ty->vla_len = len; return ty; } Type *enum_type(void) { Type *ty = new_type(TY_ENUM, 4, 4); ty->is_unsigned = true; return ty; } Type *struct_type(void) { return new_type(TY_STRUCT, 0, 1); } static Type *get_common_type(Type *ty1, Type *ty2) { if (ty1->base) return pointer_to(ty1->base); if (ty1->kind == TY_FUNC) return pointer_to(ty1); if (ty2->kind == TY_FUNC) return pointer_to(ty2); if (ty1->kind == TY_LDOUBLE || ty2->kind == TY_LDOUBLE) return ty_ldouble; if (ty1->kind == TY_DOUBLE || ty2->kind == TY_DOUBLE) return ty_double; if (ty1->kind == TY_FLOAT || ty2->kind == TY_FLOAT) return ty_float; if (ty1->size < 4) ty1 = ty_int; if (ty2->size < 4) ty2 = ty_int; if (ty1->size != ty2->size) return (ty1->size < ty2->size) ? ty2 : ty1; if (ty2->is_unsigned) return ty2; return ty1; } // For many binary operators, we implicitly promote operands so that // both operands have the same type. Any integral type smaller than // int is always promoted to int. If the type of one operand is larger // than the other's (e.g. "long" vs. "int"), the smaller operand will // be promoted to match with the other. // // This operation is called the "usual arithmetic conversion". static void usual_arith_conv(Node **lhs, Node **rhs) { if (!(*lhs)->ty || !(*rhs)->ty) { error_tok((*lhs)->tok, "internal npe error"); } Type *ty = get_common_type((*lhs)->ty, (*rhs)->ty); *lhs = new_cast(*lhs, ty); *rhs = new_cast(*rhs, ty); } void add_type(Node *node) { if (!node || node->ty) return; add_type(node->lhs); add_type(node->rhs); add_type(node->cond); add_type(node->then); add_type(node->els); add_type(node->init); add_type(node->inc); for (Node *n = node->body; n; n = n->next) add_type(n); for (Node *n = node->args; n; n = n->next) add_type(n); switch (node->kind) { case ND_NUM: node->ty = ty_int; return; case ND_ADD: case ND_SUB: case ND_MUL: case ND_DIV: case ND_REM: case ND_BINAND: case ND_BINOR: case ND_BINXOR: usual_arith_conv(&node->lhs, &node->rhs); node->ty = node->lhs->ty; return; case ND_NEG: { Type *ty = get_common_type(ty_int, node->lhs->ty); node->lhs = new_cast(node->lhs, ty); node->ty = ty; return; } case ND_ASSIGN: if (node->lhs->ty->kind == TY_ARRAY) error_tok(node->lhs->tok, "not an lvalue!"); if (node->lhs->ty->kind != TY_STRUCT) node->rhs = new_cast(node->rhs, node->lhs->ty); node->ty = node->lhs->ty; return; case ND_EQ: case ND_NE: case ND_LT: case ND_LE: usual_arith_conv(&node->lhs, &node->rhs); node->ty = ty_int; return; case ND_FUNCALL: node->ty = node->func_ty->return_ty; return; case ND_NOT: case ND_LOGOR: case ND_LOGAND: node->ty = ty_int; return; case ND_BITNOT: case ND_SHL: case ND_SHR: node->ty = node->lhs->ty; return; case ND_VAR: case ND_VLA_PTR: node->ty = node->var->ty; return; case ND_COND: if (node->then->ty->kind == TY_VOID || node->els->ty->kind == TY_VOID) { node->ty = ty_void; } else { usual_arith_conv(&node->then, &node->els); node->ty = node->then->ty; } return; case ND_COMMA: node->ty = node->rhs->ty; return; case ND_MEMBER: node->ty = node->member->ty; return; case ND_ADDR: { Type *ty = node->lhs->ty; if (ty->kind == TY_ARRAY) { node->ty = pointer_to(ty->base); } else { node->ty = pointer_to(ty); } return; } case ND_DEREF: #if 0 if (node->lhs->ty->size == 16 && (node->lhs->ty->kind == TY_FLOAT || node->lhs->ty->kind == TY_DOUBLE)) { node->ty = node->lhs->ty; } else { #endif if (!node->lhs->ty->base) { error_tok(node->tok, "invalid pointer dereference"); } if (node->lhs->ty->base->kind == TY_VOID) { /* TODO(jart): Does standard permit this? */ /* https://lkml.org/lkml/2018/3/20/845 */ error_tok(node->tok, "dereferencing a void pointer"); } node->ty = node->lhs->ty->base; #if 0 } #endif return; case ND_STMT_EXPR: if (node->body) { Node *stmt = node->body; for (;;) { if (stmt->next) { stmt = stmt->next; } else { if (stmt->kind == ND_LABEL && stmt->lhs) { stmt = stmt->lhs; } else { break; } } } if (stmt->kind == ND_EXPR_STMT) { node->ty = stmt->lhs->ty; return; } } error_tok(node->tok, "statement expression returning void is not supported"); return; case ND_LABEL_VAL: node->ty = pointer_to(ty_void); return; case ND_CAS: add_type(node->cas_addr); add_type(node->cas_old); add_type(node->cas_new); node->ty = ty_bool; if (node->cas_addr->ty->kind != TY_PTR) error_tok(node->cas_addr->tok, "pointer expected"); if (node->cas_old->ty->kind != TY_PTR) error_tok(node->cas_old->tok, "pointer expected"); return; case ND_EXCH_N: case ND_FETCHADD: case ND_FETCHSUB: case ND_FETCHXOR: case ND_FETCHAND: case ND_FETCHOR: case ND_SUBFETCH: if (node->lhs->ty->kind != TY_PTR) error_tok(node->lhs->tok, "pointer expected"); node->rhs = new_cast(node->rhs, node->lhs->ty->base); node->ty = node->lhs->ty->base; return; } }
C
/* - Andrew Bagwell - CS362 Assignment 3 - [email protected] - Test of dominion's whoseTurn function */ #include "dominion.h" #include "dominion_helpers.h" #include "rngs.h" #include <stdio.h> #include <stdlib.h> //custom assert function void assertTrue(int val1, int val2) { if (val1 != val2) printf("Test Case - FAILED\n"); else printf("Test Case - PASSED\n"); } //Testing whoseTurn int main() { struct gameState GS; int c[10] = {adventurer, ambassador, gardens, great_hall, mine, minion, smithy, salvager, steward, village}; //Standard initialization across all my tests, initializeGame(2, c, 5, &GS); printf("*************************************\n"); printf("unitTest3:\n"); printf("TESTING -- testing whoseTurn() -- BEGIN\n"); //Testing whoseTurn function initializes printf("TESTING - whoseTurn() executes successfully\n"); assertTrue(endTurn(&GS),0); printf("TESTING - whoseTurn() changes \n"); for (int i = 0; i < 27 ; i++) { printf("TESTING - %d whoseTurn after manual change to gameState property...\n", i); GS.whoseTurn = i; assertTrue(whoseTurn(&GS), i); } printf("TESTING--getCost() -- COMPLETE\n\n"); return 0; }
C
# include <stdio.h> # include <string.h> # include <stdlib.h> # include "hstio.h" # define MINVAL -1000 /* crrej_sky -- Calculate the sky for an image. Description: ------------ Computes the sky level which will be subtracted during cosmic ray rejection and added back at the end of processing. Date Author Description ---- ------ ----------- J.-C. Hsu Original 10-Feb-2000 Phil Hodge Return int instead of void, and replace exit with return; check for out of memory. */ int crrej_sky (char *sky, IODescPtr ipsci[], IODescPtr ipdq[], int nimgs, float skyval[]) { int *histgrm; /* pointer to the histogram */ int nbins; /* number of bins */ int min, max, npt; float amin, amax; float hwidth; /* histogram resolution */ float hmin; /* minimum histogram value */ float sum; int i, j, k, h; short OK = 0; FloatTwoDArray a; ShortTwoDArray b; float cr_mode (int *, int, float, float); /* -------------------------------- begin ---------------------------------- */ /* decide what to do according to sky */ if (strcmp (sky, "none") == 0) { for (k = 0; k < nimgs; ++k) { skyval[k] = 0.; } return (0); } if (strcmp (sky, "mode") != 0) { printf ("illegal sky value\n"); return (2); } /* loop all images */ initFloatData (&a); initShortData (&b); for (k = 0; k < nimgs; ++k) { /* read the data in */ getFloatData (ipsci[k], &a); if (hstio_err()) { printf ("ERROR %s\n", hstio_errmsg()); return (2); } getShortData (ipdq[k], &b); if (hstio_err()) { printf ("ERROR %s\n", hstio_errmsg()); return (2); } amin = 0.; npt = 0; sum = 0; for (j = 0; j < a.ny; ++j) { for (i = 0; i < a.nx; ++i) { if (DQPix(b,i,j) == OK) { sum += Pix(a,i,j); npt++; if (Pix(a,i,j) < amin) amin = Pix(a,i,j); } } } /* use the minimum and twice of the mean to determine the data range */ if (amin < MINVAL) min = MINVAL; else min = (int) amin - 1; amax = sum/(float)npt; if (amax <= 0.) max = 1; else max = (int) (amax + 1.) * 2; nbins = max - min + 1; /* use the mode as sky value, use the bin size of 1 (DN) */ hmin = (float) min; hwidth = 1.; /* set up the histogram array */ histgrm = calloc (nbins, sizeof(int)); if (histgrm == NULL) { printf ("ERROR out of memory in crrej_sky\n"); return (2); } /* construct the histogram */ for (j = 0; j < a.ny; ++j) { for (i = 0; i < a.nx; ++i) { if (DQPix(b,i,j) == OK) { h = (int) Pix(a,i,j) - min; if (h >= 0 && h < nbins) histgrm[h]++; } } } /* calculate the mode from the histogram */ skyval[k] = cr_mode (histgrm, nbins, hwidth, hmin); freeFloatData(&a); freeShortData(&b); free (histgrm); } return (0); }
C
//#define _BSD_SOURCE #include <time.h> #include <sys/time.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <termios.h> #include <sys/socket.h> #include <arpa/inet.h> #include <sys/types.h> #include <pwd.h> #define MAX_FLASH_SIZE 1024*8 #define MAX_COMMAND_SIZE 256 #define uint unsigned int #define uint8_t unsigned char #define uchar unsigned char #define rbuf_sz 256 char rbuf[rbuf_sz+1]; unsigned int rbuf_p=0; char wbuf[rbuf_sz+1]; char *hex_file_path=NULL; char *tty_file_path="/dev/ttyUSB0"; int fd; int ff; uchar device_address=0xff; int page_size=64; int flags=0; #define F_SELFPROG 0x01 struct program_data_struct { char data[MAX_FLASH_SIZE]; uint last_data; } prog_data; int time_diff_ms(struct timeval t1, struct timeval t2) { return (((t1.tv_sec - t2.tv_sec) * 1000000) + (t1.tv_usec - t2.tv_usec))/1000; } /* Записывает значение получив указатель на строку с хексом */ void hex2byte1 (char *hp, uint8_t *b) { *b=0; char *lp=hp+1; if ((*lp>='0')&&(*lp<='9')) { *b+=(*lp-'0'); } if ((*lp>='a')&&(*lp<='f')) { *b+=(*lp-'a'+10); } if ((*lp>='A')&&(*lp<='F')) { *b+=(*lp-'A'+10); } if ((*hp>='0')&&(*hp<='9')) { *b+=((*hp-'0')*16); } if ((*hp>='a')&&(*hp<='f')) { *b+=((*hp-'a'+10)*16); } if ((*hp>='A')&&(*hp<='F')) { *b+=((*hp-'A'+10)*16); } return; } /* Возвращает байт получив указатель на строку с хексом */ uint8_t hex2byte(char *hp) { uint8_t b; hex2byte1 (hp, &b); return b; } #define LINE_BUF_SIZE 256 char line_buf[LINE_BUF_SIZE]; /* Считывает одну строчку из HEX файла в буфер line_buf */ void read_hex_file_line() { char c; uint pp=0; do { int b=read(ff, &c, 1); if (b>0) { line_buf[pp++]=c; } else { perror("Read File Error!\n"); exit(-1); } if (pp>=LINE_BUF_SIZE) { perror("Line is full!\n"); exit(-1); } } while (c!='\n'); line_buf[pp]=0; return; } /* Проверка строки - кнстрольная сумма two'c component sum */ void check_line_crc (uchar crc) { //// СЮДА ПИСАТЬ !!!!!!!!!!! return; } /* Разбирает строку из буфера */ int parse_hex_line() { if (line_buf[0]!=':') { // проверка двоеточия perror("Нет двоеточия в начале строки!"); exit(-1); } uchar bytes=hex2byte(line_buf+1); // получаем число байт в строке uchar addr_hi=hex2byte(line_buf+1+2); // получаем старший байт адреса uchar addr_lo=hex2byte(line_buf+1+4); // получаем млажший байт адреса uchar type=hex2byte(line_buf+1+6); // получаем тип записи char *hex_data=line_buf+1+8; //указатель на начало данных uchar cksum=hex2byte(hex_data+bytes*2); // контрольная сумма после данных check_line_crc(cksum); char *daddr; switch (type) { case 0: daddr=prog_data.data+addr_lo+addr_hi*256; // адрес, куда начинаем писать for (int i=0;i<bytes;++i) { // записываем нужное число байт daddr[i]=hex2byte(hex_data+2*i); } if (addr_lo+addr_hi*256+bytes>prog_data.last_data) prog_data.last_data=addr_lo+addr_hi*256+bytes; // если общее число байт меньше обновляем break; case 1: return 1; break; default: perror("Неизвестный тип строки!"); exit(-1); break; } return 0; } /* Показывает записанные в память байты */ void show_prog_mem() { for (int i=0;i<prog_data.last_data;++i) { if (i%16==0) printf("\n%04x: ", i); printf ("%02x",(uchar)prog_data.data[i]); } printf("\n"); } /* Считывание HEX файла */ void read_hex_file() { memset(prog_data.data,0xff,MAX_FLASH_SIZE); prog_data.last_data=0; do { read_hex_file_line(); } while (parse_hex_line()==0); return; } /* Запись байта в формате hex в строку */ void byte2hex (uint8_t *b, char *hp) { uint8_t c=(*b&0xf0)>>4; if (c>9) c+=0x61-10; else c+=0x30; *hp=c; c=*b&0x0f; if (c>9) c+=0x61-10; else c+=0x30; *(hp+1)=c; return; } /* считывает строку из COM/TCP порта в rbuf */ int com_read_line () { char c; if (rbuf[rbuf_p]==0) rbuf_p=0; time_t time1, time2; time(&time1); time(&time2); while (1) { int b=read(fd, &c, 1); if (b>0) { time(&time1); if ((c!='\r')&&(c!='\n')&&(rbuf_p<rbuf_sz)) rbuf[rbuf_p++]=c; if (c=='\r') { rbuf[rbuf_p]=0; //printf(">%s",rbuf); return 1; } } else { time(&time2); if (difftime(time2,time1)>2) { return 0; } //perror("Ошибка чтения порта!"); //exit(-1); } } return 0; } /* считывает строку из COM/TCP порта в rbuf */ int com_read_line1 (unsigned int delay) { char c; if (rbuf[rbuf_p]==0) rbuf_p=0; struct timeval time1, time2; gettimeofday(&time1, NULL); gettimeofday(&time2, NULL); while (1) { int b=read(fd, &c, 1); if (b>0) { gettimeofday(&time1, NULL); if ((c!='\r')&&(c!='\n')&&(rbuf_p<rbuf_sz)) rbuf[rbuf_p++]=c; if (c=='\r') { rbuf[rbuf_p]=0; return 1; } } else { gettimeofday(&time2, NULL); if (time_diff_ms(time2,time1)>delay) { return 0; } } } return 0; } char fd_type=0; /* Отправка строки ком-порт */ void write_str (char *str) { if (fd_type==0) { //printf(">>"); for (int i=0;*(str+i)!=0;++i) { usleep(1000); write (fd,str+i,1); //printf("(%c)[%02x]\n",str[i],str[i]); } if (fd_type==1) write (fd,"\n",1); //printf ("\n"); usleep(1000); } else if (fd_type==1) { write (fd,str,strlen(str)); write (fd,"\n",1); } return; } /* Открытие порта для чтения/записи */ int open_port(void) { int fd; fd = open(tty_file_path, O_RDWR | O_NOCTTY | O_NONBLOCK); if (fd == -1) { //perror("Не открывается порт! "); //exit(-1); } else fcntl(fd, F_SETFL, 0); return (fd); } /* Открытия hex файла для чтения */ int open_file(void) { int file; if (hex_file_path==NULL) { perror("Нулевой указатель на файл! "); exit(-1); } file = open(hex_file_path,O_RDONLY); if (fd == -1) { perror("Не открывается hex-файл! "); exit(-1); } else return (file); } /* Вывод на экран строки в hex-ах */ void print_hex1 (char * p, unsigned int c) { for (int i=0;i<c;++i) printf ("%02x ",p[i]); printf("\n"); return; } /* Ожидает готовности бутлодера */ int wait_bootbegin () { time_t time1, time2; time(&time1); while (1) { time(&time2); if (difftime(time2,time1)>2) return 0; if (com_read_line()==0) continue; //printf("> %s\n",rbuf); if ((flags&F_SELFPROG)&&(strncmp(rbuf,"R00",3)==0)) { // если шлюз прогает сам себя return 2; } else if ((rbuf_p==1+4*2)&&(rbuf[0]=='P')) { // если размер как у ожидаемого пакета uchar addr=hex2byte(rbuf+1); uchar comm=hex2byte(rbuf+1+2); uchar size=hex2byte(rbuf+1+4); uchar data=hex2byte(rbuf+1+6); if ((comm==2)&&(size==1)&&(data==0)) { // если нужные команда, размер, данные if (addr==device_address||device_address==0xff) { // и если адрес подходящий device_address=addr; // запоминаем адрес break; // и выходим } } } } return 1; } /* Ожидает что бутлодер согласится программироваться */ int wait_progready () { time_t time1, time2; time(&time1); while (1) { time(&time2); if (difftime(time2,time1)>3) return 0; if (com_read_line()==0) continue; //printf(">: %s\n",rbuf); if ((flags&F_SELFPROG)&&(rbuf_p==7)&&(rbuf[0]=='R')&&(rbuf[1]=='0')&&(rbuf[2]=='2')&&(rbuf[3]=='0')&&(rbuf[4]=='0')) { // если программирование шлюза uchar data1=hex2byte(rbuf+3); uchar data2=hex2byte(rbuf+5); page_size=data2; printf ("Размер страницы: %d\n", page_size); break; } else // иначе if ((rbuf_p==1+5*2)&&(rbuf[0]=='P')) { // если размер как у ожидаемого пакета uchar addr=hex2byte(rbuf+1); uchar comm=hex2byte(rbuf+1+2); uchar size=hex2byte(rbuf+1+4); uchar data1=hex2byte(rbuf+1+6); uchar data2=hex2byte(rbuf+1+8); if ((comm==2)&&(size==2)&&(data1==2)) { // если нужные команда, размер, данные if (addr==device_address) { // и если адрес подходящий page_size=data2; // запоминаем размер страницы break; // и выходим } } } } return 1; } /* Ожидает что бутлодер схавал порцию информации */ int wait_progok () { time_t time1, time2; time(&time1); while (1) { time(&time2); if (difftime(time2,time1)>2) return 0; if (com_read_line()==0) continue; //printf(">: %s\n",rbuf); if ((flags&F_SELFPROG)&&(strncmp(rbuf,"R04",3)==0)) { // если программирование самого шлюза break; } else // иначе устройство в сети if ((rbuf_p==1+4*2)&&(rbuf[0]=='P')) { // если размер как у ожидаемого пакета uchar addr=hex2byte(rbuf+1); uchar comm=hex2byte(rbuf+1+2); uchar size=hex2byte(rbuf+1+4); uchar data1=hex2byte(rbuf+1+6); if ((comm==2)&&(size==1)&&(data1==4)) { // если нужные команда, размер, данные if (addr==device_address) { // и если адрес подходящий break; // выходим } } } } return 1; } /* Отпрака пакета */ void send_pack(uchar addr, uchar prio, uchar comm, uchar size, uchar *data) { uchar buf[MAX_COMMAND_SIZE]; buf[0]='F'; // команда F byte2hex(&addr,buf+1); // адрес byte2hex(&prio,buf+1+2); // приоритет byte2hex(&comm,buf+1+4); // команда byte2hex(&size,buf+1+6); // размер данных for (uint i=0;i<size;++i) { // данные byte2hex(data+i,buf+1+8+i*2); } buf[1+8+size*2]='\r'; // концы buf[1+8+size*2+1]=0; //printf (">>> %s\n", buf); write_str(buf); return; } /* Отправляет устройству запрос на перезапуск */ void send_reset() { if (flags&F_SELFPROG) { write_str("ZREBOOT\r"); } else { send_pack(device_address,8,3,0,NULL); } return; } /* Отправляет устройству - закончить програмирование */ void send_endprog() { if (flags&F_SELFPROG) { write_str("S05\r"); } else { uchar byte=5; // код конца программирования send_pack(device_address,8,2,1,&byte); } return; } /* Отправляет устройству - начать програмирование */ void send_beginprog() { if (flags&F_SELFPROG) { write_str("S01\r"); } else { uchar byte=1; // код начала програмирования send_pack(device_address,8,2,1,&byte); } return; } /* Настройка порта */ void port_setup() { struct termios oldtio, newtio; tcgetattr(fd,&oldtio); // save current port settings newtio.c_cflag = B9600 | CS8 | CLOCAL | CREAD; newtio.c_iflag = IGNPAR; newtio.c_oflag = 0; newtio.c_lflag = 0; newtio.c_cc[VMIN]=1; newtio.c_cc[VTIME]=0; tcflush(fd, TCIFLUSH); tcsetattr(fd,TCSANOW,&newtio); return; } /* Отправляет устройству страницу по номеру */ int prog_page(uint page_num) { uchar buf[256]; uint addr=page_num*page_size; uchar size=page_size+5; if (flags&F_SELFPROG) { // если програамирование самого шлюза buf[0]='S'; buf[1]='0'; buf[2]='3'; byte2hex(((uchar *)&addr),buf+3); // сначала младший байт byte2hex(((uchar *)&addr)+1,buf+5); // второй байт buf[7]='0'; buf[8]='0'; buf[9]='0'; buf[10]='0'; for (int i=0;i<page_size;++i) { byte2hex(prog_data.data+addr+i,buf+11+2*i); } buf[11+2*page_size]='\r'; buf[11+2*page_size+1]='\0'; write_str(buf); } else { // иначе программирование устройства в сети buf[0]=3; // команда записи страницы 3 buf[1]=(uchar)(addr>>0); // запись младшего байта 1 buf[2]=(uchar)(addr>>8); // запись старшего байта 2 buf[3]=0; // запись старшего байта 3 buf[4]=0; // запись старшего байта 4 memcpy(buf+5,prog_data.data+addr,page_size); send_pack(device_address,8,2,size,buf); } if (prog_data.last_data<=addr+page_size) return 1; return 0; } int open_rport(char* addr, int port) { int socket1; struct sockaddr_in server; socket1 = socket(AF_INET , SOCK_STREAM , 0); if (socket1 == -1) { fprintf(stderr, "Не удается создать сокет!\n"); return -1; } server.sin_addr.s_addr = inet_addr(addr); server.sin_family = AF_INET; server.sin_port = htons(port); if (connect(socket1 , (struct sockaddr *)&server , sizeof(server)) < 0) { fprintf(stderr, "Нет соединения!\n"); return -1; } fcntl(socket1, F_SETFL, O_NONBLOCK); return socket1; } /* Режим прошивки */ void flash_mode(int argc, char **argv) { printf("Flash mode>\n"); hex_file_path=argv[1]; if (argc>2) { // если указан адрес Clunet int addr=atoi(argv[2]); if (strcmp(argv[2],"self")==0) { flags|=F_SELFPROG; printf ("Режим программирование шлюза\n"); } else if ((addr<0)||(addr>255)) { fprintf(stderr,"Адрес должен быть от 0 до 255\n"); exit(-1); } device_address=addr; printf ("Clunet адрес: %d\n",device_address); } if (argc>3) { // пусть к последовательному порту tty_file_path=argv[3]; printf ("Порт: %s\n",tty_file_path); } // Обработка файла ff=open_file(); read_hex_file(); close(ff); // Если надо подключаться через удаленный порт char *dots=strstr(tty_file_path,":"); if (dots!=NULL) { char buf[128]; strcpy(buf,dots+1); int rport=atoi(buf); if ((rport<=0)||(rport>0xffff)) { fprintf(stderr,"Плохой порт: %s\n",buf); } *dots=0; strcpy(buf,tty_file_path); printf("Подключение на %s:%d...\n",buf,rport); fd=open_rport(buf,rport); if (fd < 0) { perror("Не открывается tcp порт!"); exit(-1); } fd_type=1; } else { fd=open_port(); if (fd < 0) { perror("Не открывается порт!"); exit(-1); } port_setup(); } // Работа с устройством printf ("Подключение к устройству"); do { if (device_address != 0xff) { // Если выбран конкретный адрес, можно отправить команду на перезагрузку printf(".");fflush(stdout); send_endprog(); send_reset(); } } while (wait_bootbegin()==0); printf("\n"); do { send_beginprog(); } while (wait_progready()==0); // Запись данных printf ("Прогаю"); uchar page=0; int res=0; time_t time1, time2; time(&time1); do { printf(".");fflush(stdout); do { res=prog_page(page++); } while (wait_progok()==0); } while (res==0); send_endprog(); send_endprog(); printf ("Готово!\n"); time(&time2); printf ("Время загрузки: %.1f\n",difftime(time2,time1)); sleep(1); close(fd); return; } int socket0; void init_socket0(int port) { struct sockaddr_in server; socket0 = socket(AF_INET , SOCK_STREAM , 0); fcntl(socket0, F_SETFL, O_NONBLOCK); if (socket0 == -1) { printf("Could not create socket"); exit(-1); } server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons(port); if( bind(socket0,(struct sockaddr *)&server , sizeof(server)) < 0) { perror("bind failed. Error"); exit(-1); } listen(socket0,8); return; } struct sock_cont { int sock; struct sock_cont *next; struct sock_cont *prev; char *buf; uint buf_p; struct sockaddr_in addr; } *socks=NULL; void sock_add (int sock, struct sockaddr_in addr) { struct sock_cont *new = malloc(sizeof(struct sock_cont)); new->buf = malloc(sizeof(char)*(MAX_COMMAND_SIZE+1)); new->buf_p=0; new->next=NULL; new->sock=sock; new->addr=addr; if (socks==NULL) { socks=new; new->prev=NULL; } else { struct sock_cont *ptr=socks; while (ptr->next!=NULL) { ptr=ptr->next; } ptr->next=new; new->prev=ptr; } //printf("+%d\n",new->sock); return; } void sock_remove (struct sock_cont *ptr) { close(ptr->sock); if (ptr->next!=NULL) ptr->next->prev=ptr->prev; if (ptr->prev!=NULL) ptr->prev->next=ptr->next; else socks=ptr->next; free(ptr->buf); free(ptr); return; } void sock_remove_all () { while (socks!=NULL) { sock_remove(socks); } } int try_accept () { int client_sock; struct sockaddr_in client; int c = sizeof(struct sockaddr_in); client_sock = accept(socket0, (struct sockaddr *)&client, (socklen_t*)&c); if (client_sock < 0) { return 0; } fcntl(client_sock, F_SETFL, O_NONBLOCK); puts("Connection accepted"); sock_add(client_sock,client); return 1; } void send_all_sockets(char *msg, int len) { struct sock_cont *ptr=socks; while (ptr!=NULL) { write(ptr->sock, msg , len); ptr=ptr->next; } return; } void process_sockets() { char c; char buf[64]; struct sock_cont *ptr=socks; while (ptr!=NULL) { int rs = recv(ptr->sock, &c , 1 , 0); if (rs==0) { printf ("Соединение закрыто\n"); sock_remove(ptr); } else if (rs>0) { if (ptr->buf_p<MAX_COMMAND_SIZE) ptr->buf[ptr->buf_p++]=c; if (c=='\n') { int n = sprintf(buf,"%d.%d.%d.%d:%d > ",(uchar)(ptr->addr.sin_addr.s_addr<<0), (uchar)(ptr->addr.sin_addr.s_addr>>8), (uchar)(ptr->addr.sin_addr.s_addr>>16), (uchar)(ptr->addr.sin_addr.s_addr>>24), ptr->addr.sin_port); send_all_sockets(buf,n); send_all_sockets(ptr->buf,ptr->buf_p); ptr->buf[ptr->buf_p-1]='\0'; write_str(ptr->buf); ptr->buf_p=0; } } ptr=ptr->next; } return; } struct termios oldt; int oldf; void init_stdin () { tcgetattr(STDIN_FILENO, &oldt); struct termios newt = oldt; newt.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &newt); oldf = fcntl(STDIN_FILENO, F_GETFL, 0); fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK); return; } void return_stdin () { tcsetattr(STDIN_FILENO, TCSANOW, &oldt); fcntl(STDIN_FILENO, F_SETFL, oldf); return; } int mustExit() { char c; if ((read(STDIN_FILENO,&c,1)==1)&&(c=='q')) return 1; return 0; } static int get_device_status(int fd) { struct termios t; if (fd < 0) return 0; //if (portfd_is_socket && portfd_is_connected) //return 1; return !tcgetattr(fd, &t); } void process_serial() { int res; read1: if(!get_device_status(fd)) { fprintf(stderr,"FAIL TERM...\n"); int reopen = fd == -1; close(fd); fd = -1; reopen: fd = open_port(); if (fd < 0) { goto reopen; } port_setup(); fcntl(fd, F_SETFL, O_NONBLOCK|O_NDELAY|O_NOCTTY|O_RDONLY); fprintf(stderr,"TERM OK!\n"); } res = read(fd,rbuf+rbuf_p,1); if (res==1) { if (rbuf[rbuf_p]=='\r') { ++rbuf_p; rbuf[rbuf_p]='\n'; ++rbuf_p; //send_all_sockets("Serial > ",9); send_all_sockets(rbuf,rbuf_p); rbuf_p=0; } else { ++rbuf_p; } goto read1; } else if (res<-1) { printf("%d\n", res); } return; } #define DEFAULT_TCP_PORT 8888 void server_mode(int argc, char **argv) { printf("Server mode\n"); int tcp_port=DEFAULT_TCP_PORT; if (argc>2) { tcp_port=atoi(argv[2]); if ((tcp_port<1)||tcp_port>0xffff) { fprintf(stderr,"Неверный порт %d!\n",tcp_port); exit(-1); } else { printf("Выбран порт %d\n",tcp_port); } } if (argc>3) { // пусть к последовательному порту tty_file_path=argv[3]; printf ("Порт: %s\n",tty_file_path); } init_socket0(tcp_port); fd=open_port(); if (fd < 0) { perror("Не открывается порт! "); exit(-1); } port_setup(); fcntl(fd, F_SETFL, O_NONBLOCK|O_NDELAY|O_NOCTTY|O_RDONLY); init_stdin(); do { try_accept(); process_sockets(); process_serial(); } while (!mustExit()); sock_remove_all(); close (socket0); return_stdin(); close(fd); return; } /* Отправляет устройству ping */ void send_ping(uchar addr) { if (flags&F_SELFPROG) { } else { send_pack(addr,8,0xfe,0,NULL); } return; } /* Ожидает pong */ uchar wait_pong () { while (1) { if (com_read_line1(100)==0) return 0xff; if ((rbuf_p==7)&&(rbuf[0]=='P')) { // если размер как у ожидаемого пакета uchar addr=hex2byte(rbuf+1); uchar comm=hex2byte(rbuf+1+2); uchar size=hex2byte(rbuf+1+4); if ((comm==0xff)&&(size==0)) { // если нужные команда, размер return addr; } } } return 0xff; } uchar wait_pong1 (unsigned int wait_ms, uchar wait_addr) { struct timeval time1, time2; gettimeofday(&time1, NULL); while (1) { gettimeofday(&time2, NULL); if (time_diff_ms(time2,time1)>wait_ms) { return 0xff; } if (com_read_line1(100)==0) continue; if ((rbuf_p==7)&&(rbuf[0]=='P')) { // если размер как у ожидаемого пакета uchar addr=hex2byte(rbuf+1); uchar comm=hex2byte(rbuf+1+2); uchar size=hex2byte(rbuf+1+4); if ((comm==0xff)&&(size==0)&&(addr=wait_addr)) { // если нужные команда, размер return addr; } } } return 0xff; } /* Попытка Discovery (имя устройства) */ char *try_discover (uchar address) { send_pack(address,8,0x00,0,NULL); while (1) { if (com_read_line1(2000)==0) return NULL; if ((rbuf_p>=7)&&(rbuf[0]=='P')) { uchar addr=hex2byte(rbuf+1); uchar comm=hex2byte(rbuf+1+2); uchar size=hex2byte(rbuf+1+4); if ((comm==0x01)&&(addr==address)) { // если нужные команда, размер char *buffer = (char*) malloc (size+1); for (int i=0;i<size;++i) { buffer[i]=hex2byte(rbuf+1+6+i*2); } buffer[size]=0x00; return buffer; } } } return NULL; } void open_terminal (char *port) { if (port) { // пусть к последовательному порту tty_file_path=port; printf ("Порт: %s\n",tty_file_path); } // Если надо подключаться через удаленный порт char *dots=strstr(tty_file_path,":"); if (dots!=NULL) { char buf[128]; strcpy(buf,dots+1); int rport=atoi(buf); if ((rport<=0)||(rport>0xffff)) { fprintf(stderr,"Плохой порт: %s\n",buf); } *dots=0; strcpy(buf,tty_file_path); printf("Подключение на %s:%d...\n",buf,rport); fd=open_rport(buf,rport); if (fd < 0) { perror("Не открывается tcp порт!"); exit(-1); } fd_type=1; } else { fd=open_port(); if (fd < 0) { perror("Не открывается порт!"); exit(-1); } port_setup(); } return; } /* убираем 0xff */ void chop_str(uchar *str) { int size=strlen(str); for (int i=0;i<size;++i) { if (str[i]==0xff) { str[i]=0; } } return; } /* Режим обнаружения */ void discover_mode(int argc, char **argv) { printf("Discover mode.\n"); uchar a_from=0; uchar a_to=254; if (argc==3) { a_from=atoi(argv[2]); a_to=a_from; } if (argc==4) { a_from=atoi(argv[2]); a_to=atoi(argv[3]); } open_terminal(tty_file_path); printf ("Поиск устройств...\n"); for (int i=a_from;i<=a_to;++i) { send_ping(i); uchar pong; if (a_from==a_to) { pong = wait_pong1(3000,i); } else { pong = wait_pong(); } if (pong !=0xff) { char *name = try_discover(pong); if (name != NULL) { chop_str(name); printf ("Надено устройство. Адрес: %03d (0x%02x) Имя: %s\n",pong,pong,name); free(name); } else { printf ("Надено устройство. Адрес: %03d (0x%02x) Имя: не определяется\n",pong,pong); } } } close(fd); return; } /* Попытка установить имя устройства */ char *device_try_set_name (uchar address, char *name) { uchar size=strlen(name); send_pack(address,8,0xf8,size,name); time_t time1, time2; time(&time1); while (1) { time(&time2); if (difftime(time2,time1)>2) { return NULL; } if (com_read_line1(200)==0) continue; if ((rbuf_p>=7)&&(rbuf[0]=='P')) { uchar addr=hex2byte(rbuf+1); uchar comm=hex2byte(rbuf+1+2); uchar size=hex2byte(rbuf+1+4); if ((comm==0xf9)&&(addr==address)) { // если нужные команда, размер char *buffer = (char*) malloc (size+1); for (int i=0;i<size;++i) { buffer[i]=hex2byte(rbuf+1+6+i*2); } buffer[size]=0x00; return buffer; } } } return NULL; } /* Попытка установить адрес устроства */ uchar device_try_set_addr (uchar address, uchar new_address, uint8_t param) { uint8_t COMMAND=0xfc; uint8_t COMMAND_REPLY=0xfd; uint8_t ADDRESS_REPLY=new_address; if (param==0x01) { COMMAND=0xfa; COMMAND_REPLY=0xfb; ADDRESS_REPLY=address; } send_pack(address,8,COMMAND,1,&new_address); time_t time1, time2; time(&time1); while (1) { time(&time2); if (difftime(time2,time1)>2) { return 0xff; } if (com_read_line1(200)==0) continue; if ((rbuf_p>=7)&&(rbuf[0]=='P')) { uchar addr=hex2byte(rbuf+1); uchar comm=hex2byte(rbuf+1+2); uchar size=hex2byte(rbuf+1+4); if ((comm==COMMAND_REPLY)&&(addr==ADDRESS_REPLY)&&(size==1)) { // если нужные команда, размер uchar newa=hex2byte(rbuf+1+6); return newa; } } } return 0xff; } /* Установить имя устройства */ void setname_mode(int argc, char **argv) { printf("Установка имени устройства.\n"); if (argc<3) { printf ("Не хватает параметров. Укажите setname адрес имя\n"); exit(-1); } open_terminal(tty_file_path); uchar address=atoi(argv[2]); char *name=argv[3]; printf("Установка имени устройства...\n"); char *newname = device_try_set_name(address,name); if (newname==NULL) { printf ("Ошибка установки имени '%s' для устройства с адресом %03d (0x%02x).\n",name,address,address); } else { chop_str(newname); printf ("Новое имя устройства (%s).\n",newname); } close(fd); return; } /* Установить адрес устройства */ void setaddr_mode(int argc, char **argv, uint8_t param) { printf("Установка адреса устройства.\n"); if (argc<3) { printf ("Не хватает параметров. Укажите setaddr адрес новый_адрес\n"); exit(-1); } open_terminal(tty_file_path); uchar address=atoi(argv[2]); uchar new_address=atoi(argv[3]); if (address!=new_address) { printf("Проверка нового адреса...\n"); send_ping(new_address); if (wait_pong1(1000,new_address)!=0xff) { printf ("Адрес %03d (0x%02x) уже занят.\n",new_address,new_address); char *name = try_discover(new_address); if (name != NULL) { chop_str(name); printf ("Надено устройство. Адрес: %03d (0x%02x) Имя: %s\n",new_address,new_address,name); free(name); } else { printf ("Надено устройство. Адрес: %03d (0x%02x) Имя: не определяется\n",new_address,new_address); } exit(-1); } } printf("Установка адреса устройства...\n"); uchar newa = device_try_set_addr(address,new_address,param); if (newa!=new_address) { printf ("Ошибка установки адреса %03d (0x%02x) для устройства с адресом %03d (0x%02x).\n",new_address,new_address,address,address); } else { printf ("Новый адрес устройства %03d (0x%02x).\n",newa,newa); } close(fd); return; } /* Отправка команды */ void sendcommand_mode(int argc, char **argv) { printf("Отправка команды на устройство.\n"); if (argc<3) { printf ("Не хватает параметров. Укажите sndcmd адрес команда\n"); exit(-1); } open_terminal(tty_file_path); uchar address=atoi(argv[2]); uchar command=atoi(argv[3]); printf("Отправка команды устройства...\n"); send_pack(address,3,command,0,NULL); close(fd); return; } void read_config () { struct passwd *pw = getpwuid(getuid()); const char *homedir = pw->pw_dir; printf("%s\n",homedir); char *conffile; conffile = malloc (strlen(homedir+10)); sprintf(conffile,"%s/.clunet",homedir); FILE * f = fopen(conffile,"r"); if (f) { char str[256]; while(!feof(f)) { fscanf(f,"%s\n",str); if (strstr(str,"port=")==str) { char *dot=strstr(str,"="); ++dot; tty_file_path=malloc(strlen(dot)); strcpy(tty_file_path,dot); } } fclose(f); } return; } int main (int argc, char **argv) { read_config(); if (argc<2) { // если не указаны параметры fprintf(stderr,"Надо указывать параметры!\nНапример:\n%s ./main.hex [99] [/dev/ttyUSB0]\n", argv[0]); exit(-1); } if (strcmp(argv[1],"srv")==0) { server_mode(argc,argv); } else if (strcmp(argv[1],"discover")==0) { discover_mode(argc,argv); } else if (strcmp(argv[1],"setname")==0) { setname_mode(argc,argv); } else if (strcmp(argv[1],"setaddr")==0) { setaddr_mode(argc,argv,0x00); } else if (strcmp(argv[1],"setaddreeprom")==0) { setaddr_mode(argc,argv,0x01); } else if (strcmp(argv[1],"sndcmd")==0) { sendcommand_mode(argc,argv); } else { flash_mode(argc,argv); } return 0; }
C
# include <stdlib.h> # include <stdio.h> # include <stdbool.h> # include <math.h> # include <time.h> int main ( int argc, char *argv[] ); void test_amp ( void ); void test_ampamp ( void ); void test_bang ( void ); void test_bar ( void ); void test_barbar ( void ); void test_caret ( void ); void test_lshiftlshift ( void ); void test_minus ( void ); void test_plus ( void ); void test_plusplus ( void ); void test_rshiftrshift ( void ); void test_slash ( void ); void test_star ( void ); void test_twiddle ( void ); void timestamp ( void ); /******************************************************************************/ int main ( int argc, char *argv[] ) /******************************************************************************/ /* Purpose: MAIN is the main program for C_OPERATORS. Licensing: This code is distributed under the GNU LGPL license. Modified: 28 May 2012 Author: John Burkardt */ { timestamp ( ); printf ( "\n" ); printf ( "C_OPERATORS:\n" ); printf ( " Demonstrate the operators available in C.\n" ); test_amp ( ); test_ampamp ( ); test_bang ( ); test_bar ( ); test_barbar ( ); test_caret ( ); test_lshiftlshift ( ); test_minus ( ); test_plus ( ); test_plusplus ( ); test_rshiftrshift ( ); test_slash ( ); test_star ( ); test_twiddle ( ); /* Terminate. */ printf ( "\n" ); printf ( "C_OPERATORS:\n" ); printf ( " Normal end of execution.\n" ); printf ( "\n" ); timestamp ( ); return 0; } /******************************************************************************/ void test_amp ( void ) /******************************************************************************/ /* Purpose: TEST_AMP demonstrates &. Discussion: & implements the bitwise AND function. The operation of this function is easiest to see when we look at data that is unsigned characters, that is, integers between 0 and 255. In binary, some examples include 00000000 = 0 00000011 = 3 00000101 = 5 00001101 = 13 01010000 = 80 01010101 = 85 10000000 = 128 11110010 = 242 11111111 = 255 Licensing: This code is distributed under the GNU LGPL license. Modified: 28 May 2012 Author: John Burkardt */ { unsigned char a_uchar; unsigned char b_uchar; unsigned char c_uchar; printf ( "\n" ); printf ( "TEST_AMP:\n" ); printf ( " Demonstrate &, which implements the bitwise AND operator.\n" ); printf ( " This is most useful when the data is unsigned characters,\n" ); printf ( " that is, binary integers from 0 to 255.\n" ); printf ( "\n" ); printf ( " Type A B A&B\n" ); printf ( "\n" ); a_uchar = 3; b_uchar = 5; c_uchar = a_uchar & b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 242; b_uchar = 242; c_uchar = a_uchar & b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 242; b_uchar = 13; c_uchar = a_uchar & b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 13; b_uchar = 85; c_uchar = a_uchar & b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 242; b_uchar = 85; c_uchar = a_uchar & b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 255; b_uchar = 80; c_uchar = a_uchar & b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 0; b_uchar = 128; c_uchar = a_uchar & b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); return; } /******************************************************************************/ void test_ampamp ( void ) /******************************************************************************/ /* Purpose: TEST_AMPAMP demonstrates &&. Discussion: && implements the logical AND function. In C, 0 counts as "false", and nonzero value as true. The bool datatype can also be used. Licensing: This code is distributed under the GNU LGPL license. Modified: 28 May 2012 Author: John Burkardt */ { bool a_bool; bool b_bool; bool c_bool; double a_double; double b_double; double c_double; float a_float; float b_float; float c_float; int a_int; int b_int; int c_int; printf ( "\n" ); printf ( "TEST_AMPAMP:\n" ); printf ( " Demonstrate &&, which implements the logical AND operator.\n" ); printf ( " For numeric data, 0 acts as false, nonzero as true.\n" ); printf ( "\n" ); printf ( " Type A B A&&B\n" ); printf ( "\n" ); a_bool = true; b_bool = true; c_bool = a_bool && b_bool; printf ( " bool %d %d %d\n", a_bool, b_bool, c_bool ); a_bool = true; b_bool = false; c_bool = a_bool && b_bool; printf ( " bool %d %d %d\n", a_bool, b_bool, c_bool ); a_bool = false; b_bool = true; c_bool = a_bool && b_bool; printf ( " bool %d %d %d\n", a_bool, b_bool, c_bool ); a_bool = false; b_bool = false; c_bool = a_bool && b_bool; printf ( " bool %d %d %d\n", a_bool, b_bool, c_bool ); printf ( "\n" ); a_double = 1.0; b_double = 1.0; c_double = a_double && b_double; printf ( " double %f %f %f\n", a_double, b_double, c_double ); a_double = 1.0; b_double = 0.0; c_double = a_double && b_double; printf ( " double %f %f %f\n", a_double, b_double, c_double ); a_double = 0.0; b_double = 1.0; c_double = a_double && b_double; printf ( " double %f %f %f\n", a_double, b_double, c_double ); a_double = 0.0; b_double = 0.0; c_double = a_double && b_double; printf ( " double %f %f %f\n", a_double, b_double, c_double ); printf ( "\n" ); a_float = 1.0; b_float = 1.0; c_float = a_float && b_float; printf ( " float %f %f %f\n", a_float, b_float, c_float ); a_float = 1.0; b_float = 0.0; c_float = a_float && b_float; printf ( " float %f %f %f\n", a_float, b_float, c_float ); a_float = 0.0; b_float = 1.0; c_float = a_float && b_float; printf ( " float %f %f %f\n", a_float, b_float, c_float ); a_float = 0.0; b_float = 0.0; c_float = a_float && b_float; printf ( " float %f %f %f\n", a_float, b_float, c_float ); printf ( "\n" ); a_int = 1; b_int = 1; c_int = a_int && b_int; printf ( " int %d %d %d\n", a_int, b_int, c_int ); a_int = 1; b_int = 0; c_int = a_int && b_int; printf ( " int %d %d %d\n", a_int, b_int, c_int ); a_int = 0; b_int = 1; c_int = a_int && b_int; printf ( " int %d %d %d\n", a_int, b_int, c_int ); a_int = 0; b_int = 0; c_int = a_int && b_int; printf ( " int %d %d %d\n", a_int, b_int, c_int ); return; } /******************************************************************************/ void test_bang ( void ) /******************************************************************************/ /* Purpose: TEST_BANG demonstrates !. Discussion: ! implements logical negation. In C, 0 counts as "false", and nonzero value as true. The bool datatype can also be used. Licensing: This code is distributed under the GNU LGPL license. Modified: 27 May 2012 Author: John Burkardt */ { bool a_bool; bool b_bool; double a_double; double b_double; float a_float; float b_float; int a_int; int b_int; printf ( "\n" ); printf ( "TEST_BANG:\n" ); printf ( " Demonstrate !, which implements the logical negation operator.\n" ); printf ( " For numeric data, 0 acts as false, nonzero as true.\n" ); printf ( "\n" ); printf ( " Type A !A\n" ); printf ( "\n" ); a_bool = true; b_bool = !a_bool; printf ( " bool %d %d\n", a_bool, b_bool ); a_bool = false; b_bool = !a_bool; printf ( " bool %d %d\n", a_bool, b_bool ); a_double = -1.0; b_double = !a_double; printf ( " double %f %f\n", a_double, b_double ); a_double = 0.0; b_double = !a_double; printf ( " double %f %f\n", a_double, b_double ); a_double = 1.0; b_double = !a_double; printf ( " double %f %f\n", a_double, b_double ); a_double = 3.14159265; b_double = !a_double; printf ( " double %f %f\n", a_double, b_double ); a_float = -1.0; b_float = !a_float; printf ( " float %f %f\n", a_float, b_float ); a_float = 0.0; b_float = !a_float; printf ( " float %f %f\n", a_float, b_float ); a_float = 1.0; b_float = !a_float; printf ( " float %f %f\n", a_float, b_float ); a_float = 3.14159265; b_float = !a_float; printf ( " float %f %f\n", a_float, b_float ); a_int = -1; b_int = !a_int; printf ( " int %d %d\n", a_int, b_int ); a_int = 0; b_int = !a_int; printf ( " int %d %d\n", a_int, b_int ); a_int = 1; b_int = !a_int; printf ( " int %d %d\n", a_int, b_int ); a_int = 2; b_int = !a_int; printf ( " int %d %d\n", a_int, b_int ); return; } /******************************************************************************/ void test_bar ( void ) /******************************************************************************/ /* Purpose: TEST_BAR demonstrates |. Discussion: | implements the bitwise OR function. The operation of this function is easiest to see when we look at data that is unsigned characters, that is, integers between 0 and 255. In binary, some examples include 00000000 = 0 00000011 = 3 00000101 = 5 00001101 = 13 01010000 = 80 01010101 = 85 10000000 = 128 11110010 = 242 11111111 = 255 Licensing: This code is distributed under the GNU LGPL license. Modified: 28 May 2012 Author: John Burkardt */ { unsigned char a_uchar; unsigned char b_uchar; unsigned char c_uchar; printf ( "\n" ); printf ( "TEST_BAR:\n" ); printf ( " Demonstrate |, which implements the bitwise OR operator.\n" ); printf ( " This is most useful when the data is unsigned characters,\n" ); printf ( " that is, binary integers from 0 to 255.\n" ); printf ( "\n" ); printf ( " Type A B A|B\n" ); printf ( "\n" ); a_uchar = 3; b_uchar = 5; c_uchar = a_uchar | b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 242; b_uchar = 242; c_uchar = a_uchar | b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 242; b_uchar = 13; c_uchar = a_uchar | b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 13; b_uchar = 85; c_uchar = a_uchar | b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 242; b_uchar = 85; c_uchar = a_uchar | b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 255; b_uchar = 80; c_uchar = a_uchar | b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 0; b_uchar = 128; c_uchar = a_uchar | b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); return; } /******************************************************************************/ void test_barbar ( void ) /******************************************************************************/ /* Purpose: TEST_BARBAR demonstrates ||. Discussion: || implements the logical OR function. In C, 0 counts as "false", and nonzero value as true. The bool datatype can also be used. Licensing: This code is distributed under the GNU LGPL license. Modified: 28 May 2012 Author: John Burkardt */ { bool a_bool; bool b_bool; bool c_bool; double a_double; double b_double; double c_double; float a_float; float b_float; float c_float; int a_int; int b_int; int c_int; printf ( "\n" ); printf ( "TEST_BARBAR:\n" ); printf ( " Demonstrate ||, which implements the logical OR operator.\n" ); printf ( " For numeric data, 0 acts as false, nonzero as true.\n" ); printf ( "\n" ); printf ( " Type A B A||B\n" ); printf ( "\n" ); a_bool = true; b_bool = true; c_bool = a_bool || b_bool; printf ( " bool %d %d %d\n", a_bool, b_bool, c_bool ); a_bool = true; b_bool = false; c_bool = a_bool || b_bool; printf ( " bool %d %d %d\n", a_bool, b_bool, c_bool ); a_bool = false; b_bool = true; c_bool = a_bool || b_bool; printf ( " bool %d %d %d\n", a_bool, b_bool, c_bool ); a_bool = false; b_bool = false; c_bool = a_bool || b_bool; printf ( " bool %d %d %d\n", a_bool, b_bool, c_bool ); printf ( "\n" ); a_double = 1.0; b_double = 1.0; c_double = a_double || b_double; printf ( " double %f %f %f\n", a_double, b_double, c_double ); a_double = 1.0; b_double = 0.0; c_double = a_double || b_double; printf ( " double %f %f %f\n", a_double, b_double, c_double ); a_double = 0.0; b_double = 1.0; c_double = a_double || b_double; printf ( " double %f %f %f\n", a_double, b_double, c_double ); a_double = 0.0; b_double = 0.0; c_double = a_double || b_double; printf ( " double %f %f %f\n", a_double, b_double, c_double ); printf ( "\n" ); a_float = 1.0; b_float = 1.0; c_float = a_float || b_float; printf ( " float %f %f %f\n", a_float, b_float, c_float ); a_float = 1.0; b_float = 0.0; c_float = a_float || b_float; printf ( " float %f %f %f\n", a_float, b_float, c_float ); a_float = 0.0; b_float = 1.0; c_float = a_float || b_float; printf ( " float %f %f %f\n", a_float, b_float, c_float ); a_float = 0.0; b_float = 0.0; c_float = a_float || b_float; printf ( " float %f %f %f\n", a_float, b_float, c_float ); printf ( "\n" ); a_int = 1; b_int = 1; c_int = a_int || b_int; printf ( " int %d %d %d\n", a_int, b_int, c_int ); a_int = 1; b_int = 0; c_int = a_int || b_int; printf ( " int %d %d %d\n", a_int, b_int, c_int ); a_int = 0; b_int = 1; c_int = a_int || b_int; printf ( " int %d %d %d\n", a_int, b_int, c_int ); a_int = 0; b_int = 0; c_int = a_int || b_int; printf ( " int %d %d %d\n", a_int, b_int, c_int ); return; } /******************************************************************************/ void test_caret ( void ) /******************************************************************************/ /* Purpose: TEST_CARET demonstrates ^. Discussion: ^ implements the bitwise exclusive OR function. The operation of this function is easiest to see when we look at data that is unsigned characters, that is, integers between 0 and 255. In binary, some examples include 00000000 = 0 00000011 = 3 00000101 = 5 00000110 = 6 00001101 = 13 01010000 = 80 01010101 = 85 01011000 = 88 10000000 = 128 10100111 = 167 10101111 = 175 11110010 = 242 11111111 = 255 Licensing: This code is distributed under the GNU LGPL license. Modified: 28 May 2012 Author: John Burkardt */ { unsigned char a_uchar; unsigned char b_uchar; unsigned char c_uchar; printf ( "\n" ); printf ( "TEST_CARET:\n" ); printf ( " Demonstrate ^, which implements the bitwise exclusive OR operator.\n" ); printf ( " This is most useful when the data is unsigned characters,\n" ); printf ( " that is, binary integers from 0 to 255.\n" ); printf ( "\n" ); printf ( " Type A B A^B\n" ); printf ( "\n" ); a_uchar = 3; b_uchar = 5; c_uchar = a_uchar ^ b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 242; b_uchar = 242; c_uchar = a_uchar ^ b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 242; b_uchar = 13; c_uchar = a_uchar ^ b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 13; b_uchar = 85; c_uchar = a_uchar ^ b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 242; b_uchar = 85; c_uchar = a_uchar ^ b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 255; b_uchar = 80; c_uchar = a_uchar ^ b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 0; b_uchar = 128; c_uchar = a_uchar ^ b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); return; } /******************************************************************************/ void test_lshiftlshift ( void ) /******************************************************************************/ /* Purpose: TEST_LSHIFTLSHIFT demonstrates <<. Discussion: << implements left shift. A << B has the value A * 2^B. A and B must be of an integer type. Licensing: This code is distributed under the GNU LGPL license. Modified: 27 May 2012 Author: John Burkardt */ { int a_int; int b_int; int c_int; int i; printf ( "\n" ); printf ( "TEST_LSHIFTLSHIFT:\n" ); printf ( " Demonstrate <<, which implements the left shift:\n" ); printf ( " A << B results in A * 2^B.\n" ); printf ( " Generally, B must be nonnegative.\n" ); printf ( " Moreover, B should not be so large that the result overflows.\n" ); printf ( "\n" ); printf ( " Type A B A<<B\n" ); printf ( "\n" ); for ( i = -1; i < 32; i++ ) { a_int = 11; b_int = i; c_int = a_int << b_int; printf ( " int %d %d %d\n", a_int, b_int, c_int ); } return; } /******************************************************************************/ void test_minus ( void ) /******************************************************************************/ /* Purpose: TEST_MINUS demonstrates -. Discussion: - implements subtraction. Licensing: This code is distributed under the GNU LGPL license. Modified: 27 May 2012 Author: John Burkardt */ { char a_char; char b_char; char c_char; double a_double; double b_double; double c_double; float a_float; float b_float; float c_float; int a_int; int b_int; int c_int; unsigned char a_uchar; unsigned char b_uchar; unsigned char c_uchar; printf ( "\n" ); printf ( "TEST_MINUS:\n" ); printf ( " Demonstrate -, which carries out subtraction:\n" ); printf ( "\n" ); printf ( " Type A B A-B\n" ); printf ( "\n" ); a_char = 'Z'; b_char = 'b'; c_char = a_char - b_char; printf ( " char %c %c %d\n", a_char, b_char, c_char ); a_double = 9.25; b_double = 3.12; c_double = a_double - b_double; printf ( " double %f %f %f\n", a_double, b_double, c_double ); a_float = 9.25; b_float = 3.12; c_float = a_float - b_float; printf ( " float %f %f %f\n", a_float, b_float, c_float ); a_int = 11; b_int = 2; c_int = a_int - b_int; printf ( " int %d %d %d\n", a_int, b_int, c_int ); a_uchar = 'Z'; b_uchar = 'b'; c_uchar = a_uchar - b_uchar; printf ( " unsigned char %c %c %d\n", a_uchar, b_uchar, c_uchar ); return; } /******************************************************************************/ void test_plus ( void ) /******************************************************************************/ /* Purpose: TEST_PLUS demonstrates +. Discussion: + implements addition. Licensing: This code is distributed under the GNU LGPL license. Modified: 27 May 2012 Author: John Burkardt */ { char a_char; char b_char; char c_char; double a_double; double b_double; double c_double; float a_float; float b_float; float c_float; int a_int; int b_int; int c_int; unsigned char a_uchar; unsigned char b_uchar; unsigned char c_uchar; printf ( "\n" ); printf ( "TEST_PLUS:\n" ); printf ( " Demonstrate +, which carries out addition:\n" ); printf ( "\n" ); printf ( " Type A B A+B\n" ); printf ( "\n" ); a_char = 'a'; b_char = 'b'; c_char = a_char + b_char; printf ( " char %c %c %d\n", a_char, b_char, c_char ); a_double = 1.25; b_double = 3.12; c_double = a_double + b_double; printf ( " double %f %f %f\n", a_double, b_double, c_double ); a_float = 1.25; b_float = 3.12; c_float = a_float + b_float; printf ( " float %f %f %f\n", a_float, b_float, c_float ); a_int = 1; b_int = 2; c_int = a_int + b_int; printf ( " int %d %d %d\n", a_int, b_int, c_int ); a_uchar = 'a'; b_uchar = 'b'; c_uchar = a_uchar + b_uchar; printf ( " unsigned char %c %c %d\n", a_uchar, b_uchar, c_uchar ); return; } /******************************************************************************/ void test_plusplus ( void ) /******************************************************************************/ /* Purpose: TEST_PLUSPLUS demonstrates ++. Discussion: ++ implements increment by 1. Licensing: This code is distributed under the GNU LGPL license. Modified: 27 May 2012 Author: John Burkardt */ { char a_char; char b_char; char c_char; double a_double; double b_double; double c_double; float a_float; float b_float; float c_float; int a_int; int b_int; int c_int; unsigned char a_uchar; unsigned char b_uchar; unsigned char c_uchar; printf ( "\n" ); printf ( "TEST_PLUSPLUS:\n" ); printf ( " Demonstrate ++, which increments by 1:\n" ); printf ( "\n" ); printf ( " We execute the following statements:\n" ); printf ( "\n" ); printf ( " A = value;\n" ); printf ( " B = A;\n" ); printf ( " C = A++;\n" ); printf ( "\n" ); printf ( " Type A B C\n" ); printf ( "\n" ); a_char = 'a'; b_char = a_char; c_char = a_char++; printf ( " char %c %c %c\n", a_char, b_char, c_char ); a_double = 1.25; b_double = a_double; c_double = a_double++; printf ( " double %f %f %f\n", a_double, b_double, c_double ); a_float = 1.25; b_float = a_float; c_float = a_float++; printf ( " float %f %f %f\n", a_float, b_float, c_float ); a_int = 1; b_int = a_int; c_int = a_int++; printf ( " int %d %d %d\n", a_int, b_int, c_int ); a_uchar = 'a'; b_uchar = a_uchar; c_uchar = a_uchar++; printf ( " unsigned char %c %c %c\n", a_uchar, b_uchar, c_uchar ); printf ( "\n" ); printf ( " We execute the following statements:\n" ); printf ( "\n" ); printf ( " A = value;\n" ); printf ( " B = A;\n" ); printf ( " C = ++A;\n" ); printf ( "\n" ); printf ( " Type A B C\n" ); printf ( "\n" ); a_char = 'a'; b_char = a_char; c_char = ++a_char; printf ( " char %c %c %c\n", a_char, b_char, c_char ); a_double = 1.25; b_double = a_double; c_double = ++a_double; printf ( " double %f %f %f\n", a_double, b_double, c_double ); a_float = 1.25; b_float = a_float; c_float = ++a_float; printf ( " float %f %f %f\n", a_float, b_float, c_float ); a_int = 1; b_int = a_int; c_int = ++a_int; printf ( " int %d %d %d\n", a_int, b_int, c_int ); a_uchar = 'a'; b_uchar = a_uchar; c_uchar = ++a_uchar; printf ( " unsigned char %c %c %c\n", a_uchar, b_uchar, c_uchar ); return; } /******************************************************************************/ void test_rshiftrshift ( void ) /******************************************************************************/ /* Purpose: TEST_RSHIFTRSHIFT demonstrates >>. Discussion: >> implements right shift. A >> B has the value A / 2^B. A and B must be of an integer type. Licensing: This code is distributed under the GNU LGPL license. Modified: 27 May 2012 Author: John Burkardt */ { int a_int; int b_int; int c_int; int i; printf ( "\n" ); printf ( "TEST_RSHIFTRSHIFT:\n" ); printf ( " Demonstrate >>, which implements the right shift:\n" ); printf ( " A >> B results in A / 2^B.\n" ); printf ( " Generally, B must be nonnegative.\n" ); printf ( " Moreover, B should not be so large that the result underflows.\n" ); printf ( "\n" ); printf ( " When A is negative, the shift might be logical or arithmetic.\n" ); printf ( "\n" ); printf ( " Type A B A>>B\n" ); printf ( "\n" ); a_int = 3239; for ( i = -1; i < 32; i++ ) { b_int = i; c_int = a_int >> b_int; printf ( " int %d %d %d\n", a_int, b_int, c_int ); } printf ( "\n" ); a_int = -3239; for ( i = -1; i < 32; i++ ) { b_int = i; c_int = a_int >> b_int; printf ( " int %d %d %d\n", a_int, b_int, c_int ); } return; } /******************************************************************************/ void test_slash ( void ) /******************************************************************************/ /* Purpose: TEST_SLASH demonstrates /. Discussion: * implements division. Licensing: This code is distributed under the GNU LGPL license. Modified: 27 May 2012 Author: John Burkardt */ { char a_char; char b_char; char c_char; double a_double; double b_double; double c_double; float a_float; float b_float; float c_float; int a_int; int b_int; int c_int; unsigned char a_uchar; unsigned char b_uchar; unsigned char c_uchar; printf ( "\n" ); printf ( "TEST_SLASH:\n" ); printf ( " Demonstrate /, which carries out division:\n" ); printf ( "\n" ); printf ( " Type A B A/B\n" ); printf ( "\n" ); a_char = 'a'; b_char = 'b'; c_char = a_char / b_char; printf ( " char %c %c %d\n", a_char, b_char, c_char ); a_char = 'a'; b_char = 'a'; c_char = a_char / b_char; printf ( " char %c %c %d\n", a_char, b_char, c_char ); a_double = 20.00; b_double = 3.00; c_double = a_double / b_double; printf ( " double %f %f %f\n", a_double, b_double, c_double ); a_float = 20.00; b_float = 3.00; c_float = a_float / b_float; printf ( " float %f %f %f\n", a_float, b_float, c_float ); a_int = 20; b_int = 3; c_int = a_int / b_int; printf ( " int %d %d %d\n", a_int, b_int, c_int ); a_uchar = 'a'; b_uchar = 'a'; c_uchar = a_uchar / b_uchar; printf ( " unsigned char %c %c %d\n", a_uchar, b_uchar, c_uchar ); return; } /******************************************************************************/ void test_star ( void ) /******************************************************************************/ /* Purpose: TEST_STAR demonstrates *. Discussion: * implements multiplication. Licensing: This code is distributed under the GNU LGPL license. Modified: 27 May 2012 Author: John Burkardt */ { char a_char; char b_char; char c_char; double a_double; double b_double; double c_double; float a_float; float b_float; float c_float; int a_int; int b_int; int c_int; unsigned char a_uchar; unsigned char b_uchar; unsigned char c_uchar; printf ( "\n" ); printf ( "TEST_STAR:\n" ); printf ( " Demonstrate *, which carries out multiplication:\n" ); printf ( "\n" ); printf ( " Type A B A*B\n" ); printf ( "\n" ); a_char = 'a'; b_char = 'b'; c_char = a_char * b_char; printf ( " char %c %c %d\n", a_char, b_char, c_char ); a_double = 1.25; b_double = 3.12; c_double = a_double * b_double; printf ( " double %f %f %f\n", a_double, b_double, c_double ); a_float = 1.25; b_float = 3.12; c_float = a_float * b_float; printf ( " float %f %f %f\n", a_float, b_float, c_float ); a_int = 10; b_int = -7; c_int = a_int * b_int; printf ( " int %d %d %d\n", a_int, b_int, c_int ); a_uchar = 'a'; b_uchar = 'b'; c_uchar = a_uchar * b_uchar; printf ( " unsigned char %c %c %d\n", a_uchar, b_uchar, c_uchar ); return; } /******************************************************************************/ void test_twiddle ( void ) /******************************************************************************/ /* Purpose: TEST_TWIDDLE demonstrates ~. Discussion: ~ implements the bitwise ones complement function. The operation of this function is easiest to see when we look at data that is unsigned characters, that is, integers between 0 and 255. In binary, some examples include 00000000 = 0 00000011 = 3 00000101 = 5 00001101 = 13 01010000 = 80 01010101 = 85 10000000 = 128 11110010 = 242 11111111 = 255 Licensing: This code is distributed under the GNU LGPL license. Modified: 28 May 2012 Author: John Burkardt */ { unsigned char a_uchar; unsigned char b_uchar; unsigned char c_uchar; char a_char; char b_char; char c_char; printf ( "\n" ); printf ( "TEST_TWIDDLE:\n" ); printf ( " Demonstrate ~, which implements the ones complement operator.\n" ); printf ( " This is most useful when the data is unsigned characters,\n" ); printf ( " that is, binary integers from 0 to 255.\n" ); printf ( "\n" ); printf ( " Type A ~A A+~A\n" ); printf ( "\n" ); a_uchar = 0; b_uchar = ~ a_uchar; c_uchar = a_uchar + b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 1; b_uchar = ~ a_uchar; c_uchar = a_uchar + b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 2; b_uchar = ~ a_uchar; c_uchar = a_uchar + b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 3; b_uchar = ~ a_uchar; c_uchar = a_uchar + b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 5; b_uchar = ~ a_uchar; c_uchar = a_uchar + b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 13; b_uchar = ~ a_uchar; c_uchar = a_uchar + b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 80; b_uchar = ~ a_uchar; c_uchar = a_uchar + b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 85; b_uchar = ~ a_uchar; c_uchar = a_uchar + b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 128; b_uchar = ~ a_uchar; c_uchar = a_uchar + b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 242; b_uchar = ~ a_uchar; c_uchar = a_uchar + b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 254; b_uchar = ~ a_uchar; c_uchar = a_uchar + b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); a_uchar = 255; b_uchar = ~ a_uchar; c_uchar = a_uchar + b_uchar; printf ( " uchar %3d %3d %3d\n", a_uchar, b_uchar, c_uchar ); printf ( "\n" ); a_char = 0; b_char = ~ a_char; c_char = a_char + b_char; printf ( " char %4d %4d %4d\n", a_char, b_char, c_char ); a_char = 1; b_char = ~ a_char; c_char = a_char + b_char; printf ( " char %4d %4d %4d\n", a_char, b_char, c_char ); a_char = 2; b_char = ~ a_char; c_char = a_char + b_char; printf ( " char %4d %4d %4d\n", a_char, b_char, c_char ); a_char = 3; b_char = ~ a_char; c_char = a_char + b_char; printf ( " char %4d %4d %4d\n", a_char, b_char, c_char ); a_char = 5; b_char = ~ a_char; c_char = a_char + b_char; printf ( " char %4d %4d %4d\n", a_char, b_char, c_char ); a_char = 13; b_char = ~ a_char; c_char = a_char + b_char; printf ( " char %4d %4d %4d\n", a_char, b_char, c_char ); a_char = 80; b_char = ~ a_char; c_char = a_char + b_char; printf ( " char %4d %4d %4d\n", a_char, b_char, c_char ); a_char = 85; b_char = ~ a_char; c_char = a_char + b_char; printf ( " char %4d %4d %4d\n", a_char, b_char, c_char ); a_char = 127; b_char = ~ a_char; c_char = a_char + b_char; printf ( " char %4d %4d %4d\n", a_char, b_char, c_char ); a_char = -1; b_char = ~ a_char; c_char = a_char + b_char; printf ( " char %4d %4d %4d\n", a_char, b_char, c_char ); a_char = -2; b_char = ~ a_char; c_char = a_char + b_char; printf ( " char %4d %4d %4d\n", a_char, b_char, c_char ); a_char = -3; b_char = ~ a_char; c_char = a_char + b_char; printf ( " char %4d %4d %4d\n", a_char, b_char, c_char ); a_char = -4; b_char = ~ a_char; c_char = a_char + b_char; printf ( " char %4d %4d %4d\n", a_char, b_char, c_char ); a_char = -128; b_char = ~ a_char; c_char = a_char + b_char; printf ( " char %4d %4d %4d\n", a_char, b_char, c_char ); return; } /******************************************************************************/ void timestamp ( void ) /******************************************************************************/ /* Purpose: TIMESTAMP prints the current YMDHMS date as a time stamp. Example: 31 May 2001 09:45:54 AM Licensing: This code is distributed under the GNU LGPL license. Modified: 24 September 2003 Author: John Burkardt Parameters: None */ { # define TIME_SIZE 40 static char time_buffer[TIME_SIZE]; const struct tm *tm; time_t now; now = time ( NULL ); tm = localtime ( &now ); strftime ( time_buffer, TIME_SIZE, "%d %B %Y %I:%M:%S %p", tm ); printf ( "%s\n", time_buffer ); return; # undef TIME_SIZE }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* builtin_setenv.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fmallist <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/03/02 17:27:19 by fmallist #+# #+# */ /* Updated: 2020/08/11 20:08:08 by fmallist ### ########.fr */ /* */ /* ************************************************************************** */ #include "../minishell.h" static char *create_new_var(char *name, char *value) { char *new_var; new_var = NULL; if (!(new_var = ft_memalloc(sizeof(char) * (ft_strlen(name) + ft_strlen(value) + 2)))) malloc_error(); ft_strcpy(new_var, name); ft_strcat(new_var, "="); ft_strcat(new_var, value); return (new_var); } void override_env(char ***env, char *value, t_hash_table **ht, int i) { replace_env(env, value, i); recreate_ht(*env, ht); } static void help(char *name, char *value, char ***env, char ***new_env) { char *new_var; char **tmp; new_var = create_new_var(name, value); append_ev(new_env, *env, new_var); tmp = *env; *env = *new_env; delete_table(&tmp); } void delete_twostr(char **a, char **b) { ft_strdel(a); ft_strdel(b); } int builtin_setenv(char **args, char ***env, t_hash_table **ht) { int i; int override; char **new_env; char *value; char *name; new_env = NULL; if ((override = is_bad_usage(args)) == -1) return (-1); name = strip_env_var(args[1]); value = ft_strsub(args[1], ft_strlen_fp(args[1], is_not_equal) + 1, ft_strlen(args[1] + ft_strlen_fp(args[1], is_not_equal))); if (((i = find_env(*env, name)) != -1) && override) override_env(env, value, ht, i); else { help(name, value, env, &new_env); recreate_ht(*env, ht); } delete_twostr(&name, &value); return (1); }
C
/** * @file dec2bin.c * @author your name ([email protected]) * @brief * @version 0.1 * @date 2020-10-07 * * @copyright Copyright (c) 2020 * */ #include <stdio.h> #include <stdlib.h> /** * @brief * */ #define APP_USAGE "Pouziti: dec2bin <pozitivni-hodnota>\n" #define MAX_OUTPUT_LENGTH 32 int main(int argc, char *argv[]){ char bin_out[MAX_OUTPUT_LENGTH] = { 0 }; int dec,i; /** kontrola, jestli uživatel zadal parametr*/ if(argc < 2){ printf(APP_USAGE); return EXIT_FAILURE; } /* Převod řetězce na celé číslo a zkontrolovali jsme, že je <=0.*/ dec = atoi(argv[1]); if(dec <= 0){ printf(APP_USAGE); return EXIT_FAILURE; } printf("%d(d) =", dec); i = 0; while (dec != 0) { bin_out[i] = dec % 2 + '0'; dec /= 2; i++; } for(i--; i >= 0; i--){ printf("%c",bin_out[i]); } return EXIT_SUCCESS; }
C
/* This file is part of podds. podds is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. podds is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with podds. If not, see <http://www.gnu.org/licenses/>. */ #include <stdint.h> #include "xorshift.h" uint32_t xorshift32_rand(uint32_t * seed) { seed[0] ^= seed[0] << 13; seed[0] ^= seed[0] >> 17; seed[0] ^= seed[0] << 5; return seed[0]; } uint32_t xorshift32_randint(uint32_t * seed, uint32_t hi) { return (uint32_t)((double)xorshift32_rand(seed) / ((double)UINT32_MAX + 1) * hi); }
C
#include <stdio.h> #include <math.h> int isprime(int n){ if(n<=1) return 0; if(n<=3) return 1; if(n%2==0 || n%3 == 0) return 0; int i; int sq = sqrt(n); for (i=5; i<=sq; i=i+6) // printf("%d %d\n",i, i+2); if (n%i == 0 || n%(i+2) == 0) return 0; return 1; } /*5 4 3 6 1 2 7 8 9*/ int main(){ int denominator = 5;// 1 3 5 7 9 int numerator = 3; //3 5 7 int gap = 4; int corner = 5; //begin with 9 while(((float)numerator/denominator) > 0.10 ){ int corner2 = corner*corner-gap; int corner3 = corner*corner-2*gap; int corner4 = corner*corner-3*gap; //printf("%d %d %d %d\n",corner*corner,corner2,corner3,corner4); numerator+=isprime(corner2); numerator+=isprime(corner3); numerator+=isprime(corner4); denominator+=4; gap+=2; corner+=2; printf("%f\n",(float)numerator/denominator); } //printf("%d %d\n",gap,corner); printf("%d\n",corner-2); }
C
/* * Dada una base en formato 8 bits, regresa su representacion en string, muy simple */ #include "bevolucion.h" char * nombre_par_base (int8_t n) { char *ptr; switch (n) { case AT: ptr = "AT\0"; break; case TA: ptr = "TA\0"; break; case CG: ptr = "CG\0"; break; case GC: ptr = "GC\0"; break; case AU: ptr = "AU\0"; break; case UA: ptr = "UA\0"; break; default: fprintf (stderr, "ERROR, %x no representa ningun par complementario de bases nitrogenadas\n", n); ptr = NULL; exit (EXIT_FAILURE); } return ptr; }
C
#include "xfifo.h" #include "xfifo_internal.h" xfifo_t xfifo_init(unsigned int fifo[], unsigned int n) { fifo[LEN_INDEX] = n+FIFO_START+1; fifo[IPOS_INDEX] = FIFO_START+1; fifo[OPOS_INDEX] = FIFO_START; fifo[SPOS_INDEX] = FIFO_START+1; fifo[OVERFLOW_INDEX] = 1; return ((xfifo_t) &fifo[0]); } unsigned int xfifo_push(xfifo_t fifo0, unsigned int x) { unsigned int ipos; unsigned int opos; unsigned int len; volatile unsigned int *fifo = (volatile unsigned int *) fifo0; ipos = fifo[IPOS_INDEX]; opos = fifo[OPOS_INDEX]; len = fifo[LEN_INDEX]; if (ipos!=opos) { fifo[ipos] = x; ipos++; if (ipos == len) ipos = FIFO_START; fifo[IPOS_INDEX] = ipos; } else return 0; return 1; ; } unsigned int xfifo_pull(xfifo_t fifo0, unsigned int *success) { volatile unsigned int *fifo = (volatile unsigned int *) fifo0; unsigned int ipos = fifo[IPOS_INDEX]; unsigned int opos = fifo[OPOS_INDEX]; unsigned int len = fifo[LEN_INDEX]; opos++; if (opos == len) opos = FIFO_START; if (ipos!=opos) { unsigned int x = fifo[opos]; fifo[OPOS_INDEX]=opos; *success = 1; return x; } else *success = 0; return 0; } unsigned int xfifo_num_elements(xfifo_t fifo0) { volatile unsigned int *fifo = (volatile unsigned int *) fifo0; int n; int ipos = fifo[IPOS_INDEX]; int opos = fifo[OPOS_INDEX]; n = ipos - opos; if (ipos <= opos ) { n += fifo[LEN_INDEX] - (FIFO_START + 1); } else { n -= 1; } return n; } unsigned int xfifo_is_empty(xfifo_t fifo0) { volatile unsigned int *fifo = (volatile unsigned int *) fifo0; unsigned int ipos = fifo[IPOS_INDEX]; unsigned int opos = fifo[OPOS_INDEX]; unsigned int len = fifo[LEN_INDEX]; opos++; if (opos == len) opos = FIFO_START; return (ipos==opos); } unsigned int xfifo_is_full(xfifo_t fifo0) { volatile unsigned int *fifo = (volatile unsigned int *) fifo0; unsigned int ipos; unsigned int opos; ipos = fifo[IPOS_INDEX]; opos = fifo[OPOS_INDEX]; return (ipos==opos); } void xfifo_blocking_push(xfifo_t fifo0, unsigned int x) { volatile unsigned int *fifo = (volatile unsigned int *) fifo0; unsigned int ipos; unsigned int opos; unsigned int len; ipos = fifo[IPOS_INDEX]; // This loop is dangerous, it relies on the optimizers not // lifting the array access out of the loop. do { opos = fifo[OPOS_INDEX]; } while (ipos==opos); len = fifo[LEN_INDEX]; fifo[ipos] = x; ipos++; if (ipos == len) ipos = FIFO_START; fifo[IPOS_INDEX] = ipos; return; } unsigned int xfifo_blocking_pull(xfifo_t fifo0) { volatile unsigned int *fifo = (volatile unsigned int *) fifo0; unsigned int ipos; unsigned int opos; unsigned int len; unsigned int x; len = fifo[LEN_INDEX]; opos = fifo[OPOS_INDEX]; opos++; if (opos == len) opos = FIFO_START; // This loop is dangerous, it relies on the optimizers not // lifting the array access out of the loop. do { ipos = fifo[IPOS_INDEX]; } while (ipos == opos); x = fifo[opos]; fifo[OPOS_INDEX]=opos; return x; }
C
#include <stdio.h> #include "batalla.h" #include "perfil.h" #include <time.h> #include <stdlib.h> #include <ctype.h> void validar_respuesta_crear( char* rta ){ while( ( *rta ) != 'S' && ( *rta ) !='N' ){ printf( "ERROR. No es una respuesta valida. Si quiere crear un personaje insgre 'S' o 's'\nEn caso contrario ingrese 'N' o 'n'.\n" ); scanf( " %c", rta ); *rta=toupper( *rta ); } } void cargar_mapa_inicial( char terreno[ MAX_TERRENO_FIL ][ MAX_TERRENO_COL ] ){ for( int fila = PRIMER_FILA; fila<MAX_TERRENO_FIL; fila++ ){ for( int columna = PRIMER_COLUMNA; columna<MAX_TERRENO_COL; columna++ ){ terreno[ fila ][ columna ] = TERRENO_VACIO; } } } void cargar_personajes( juego_t* juego ){ for( int i=0; i< juego->cantidad_isengard; i++ ){ juego->terreno[ juego->isengard[ i ].fila ][ juego->isengard[ i ].columna ]=juego->isengard[ i ].codigo; } for( int r=0; r<juego->cantidad_rohan; r++ ){ juego->terreno[ juego->rohan[ r ].fila ][ juego->rohan[ r ].columna ]=juego->rohan[ r ].codigo; } } void actualizar_terreno( juego_t* juego ){ for( int fila = PRIMER_FILA; fila < MAX_TERRENO_FIL; fila++ ){ for( int col = PRIMER_COLUMNA; col<MAX_TERRENO_COL; col++ ){ printf( " %c\t",juego->terreno[ fila ][ col ] ); } printf( "\n" ); } printf( "\n" ); } void plus( jugador_t jugador, juego_t* juego ){ if( jugador.tipo == ROHAN ){ juego->plus_rohan = jugador.intensidad * ( rand()%RANGO_PLUS ); }else{ juego->plus_isengard = jugador.intensidad * ( rand()%RANGO_PLUS ); } } void inicializar_personajes_fijos( personaje_t* personaje, int plus ){ personaje->vida = VIDA_ELFO_URUK - plus; personaje->ataque = ATAQUE_ELFO_URUK + plus; personaje->pts_energia = PTS_ELFO_URUK; } void inicializar_personajes_movibles( personaje_t* personaje, int plus ){ personaje->vida = VIDA_HOMBRE_ORCO - plus; personaje->ataque = ATAQUE_HOMBRE_ORCO + plus; personaje->pts_energia = PTS_HOMBRE_ORCO; } void posicionar_fijo_aleatorio( int* cantidad, personaje_t personaje, char terreno[ MAX_TERRENO_FIL ][ MAX_TERRENO_COL ], personaje_t vec_personajes[ MAX_PERSONAJES ], int amplitud ){ int fil_rndm; int col_rndm; for( ; ( *cantidad )<PERSONAJES_INICIALES; ( *cantidad )++ ){ fil_rndm = ( rand()%4 )+amplitud; col_rndm = rand()%10; for( int i=0; i<( *cantidad ); i++ ){ while( vec_personajes[ i ].fila == fil_rndm && vec_personajes[ i ].columna == col_rndm ){ fil_rndm = ( rand()%4 )+amplitud; col_rndm = rand()%10; } } vec_personajes[ ( *cantidad ) ] = personaje; vec_personajes[ ( *cantidad ) ].fila = fil_rndm; vec_personajes[ ( *cantidad ) ].columna = col_rndm; } } void posicionar_movil_aleatorio( int* cantidad, personaje_t personaje, char terreno[ MAX_TERRENO_FIL ][ MAX_TERRENO_COL ], personaje_t vec_personajes[ MAX_PERSONAJES ], jugador_t* jugador, int fila ){ int col_rndm; col_rndm = rand()%10; while( ( terreno[ fila ][ col_rndm ] )!=TERRENO_VACIO ){ col_rndm = rand()%10; } vec_personajes[ ( *cantidad ) ] = personaje; vec_personajes[ ( *cantidad ) ].fila = fila; vec_personajes[ ( *cantidad ) ].columna = col_rndm; ( *cantidad )++; ( *jugador ).energia -= personaje.pts_energia; } void posicionar_moviles( char terreno[ MAX_TERRENO_FIL ][ MAX_TERRENO_COL ], int fila_inicial, personaje_t vec_personajes[ MAX_PERSONAJES ], personaje_t personaje, int* cantidad_personajes, char fila[ 10 ], char bando[ 15 ] ){ int col; printf( "Elija una columna ( del 0 al 9 ) de la %s fila donde quiera posicionar al %s.\n", fila, bando ); scanf( "%i", &col ); while( ( col > ULTIMA_COLUMNA ) || col < PRIMER_COLUMNA ){ printf( "ERROR: el numero no es valido.\nElija una columna ( del 0 al 9 ) de la %s fila donde quiera posicionar al %s.\n", fila, bando ); scanf( "%i", &col ); } while( terreno[ fila_inicial ][ col ]!= TERRENO_VACIO ){ printf( "ERROR: Ese espacio esta ocupado.\nElija una columna ( del 0 al 9 ) de la %s fila donde quiera posicionar al %s.\n", fila, bando ); scanf( "%i", &col ); } vec_personajes[ ( *cantidad_personajes ) ] = personaje; vec_personajes[ ( *cantidad_personajes ) ].fila = fila_inicial; vec_personajes[ ( *cantidad_personajes ) ].columna = col; ( *cantidad_personajes )++; } void posicionar_fijos( int primer_fila_campo, int ultima_fila_campo, char rango[ 15 ], char pers[ 5 ], char terreno[ MAX_TERRENO_FIL ][ MAX_TERRENO_COL ], personaje_t vec_personajes[ MAX_PERSONAJES ], int* cantidad_personajes, personaje_t personaje ){ int fila; int col; printf( "Elija una fila de su mitad de terreno donde quiera ubicar a su %s.\n", pers ); scanf( "%i", &fila ); while( ( fila < primer_fila_campo ) || ( fila > ultima_fila_campo ) ){ printf( "ERROR: el numero no es valido.\nElija una fila %s donde quiera posicionar al %s.\n", rango, pers ); scanf( "%i", &fila ); } printf( "Elija una columna donde quiera ubicar a su %s.\n", pers ); scanf( "%i", &col ); while( ( col < PRIMER_COLUMNA ) || ( col ) > ULTIMA_COLUMNA ){ printf( "ERROR: el numero no es valido.\nElija una columna ( del 0 al 9 ) donde quiera posicionar al %s.\n", pers ); scanf( "%i", &col ); } while( terreno[ fila ][ col ]!= TERRENO_VACIO ){ printf( "ERROR: Ese espacio esta ocupado.\nElija una fila %s donde quiera posicionar al %s.\n", rango, pers ); scanf( "%i", &fila ); while( ( fila < primer_fila_campo ) || ( fila > ultima_fila_campo ) ){ printf( "ERROR: el numero no es valido.\nElija una fila %s donde quiera posicionar al %s.\n", rango, pers ); scanf( "%i", &fila ); } printf( "ERROR: Ese espacio esta ocupado.\nElija una columna ( del 0 al 9 ) donde quiera posicionar al %s.\n", pers ); scanf( "%i", &col ); while( ( col < PRIMER_COLUMNA ) || ( col > ULTIMA_COLUMNA ) ){ printf( "ERROR: el numero no es valido.\nElija una columna ( del 0 al 9 ) donde quiera posicionar al %s.\n", pers ); scanf( "%i", &col ); } } vec_personajes[ ( *cantidad_personajes ) ] = personaje; vec_personajes[ ( *cantidad_personajes ) ].fila = fila; vec_personajes[ ( *cantidad_personajes ) ].columna = col; ( *cantidad_personajes )++; } void personaje_murio( personaje_t personaje[ MAX_PERSONAJES ], int i, int* cantidad ){ if( personaje[ i ].vida == 0 ){ for( int j=i+1; j<( *cantidad ); j++ ){ personaje[ i ] = personaje[ j ]; } ( *cantidad )--; } } void personaje_llego( int* cantidad, personaje_t personaje[ MAX_PERSONAJES ], int* llegadas, int i ){ if( personaje[ i ].codigo == HOMBRE && personaje[ i ].fila == PRIMER_FILA && personaje[ i ].vida > 0 ){ ( *llegadas )++; for( int j=i+1; j<( *cantidad ); j++ ){ personaje[ i ] = personaje[ j ]; } ( *cantidad )--; }else if( personaje[ i ].codigo == ORCO && personaje[ i ].fila == ULTIMA_FILA && personaje[ i ].vida > 0 ){ ( *llegadas )++; for( int j=i+1; j<( *cantidad ); j++ ){ personaje[ i ] = personaje[ j ]; } ( *cantidad )--; } } void eliminar_personaje( int* cantidad, personaje_t personaje[ MAX_PERSONAJES ], int* llegadas ){ for( int i=0; i<( *cantidad ); i++ ){ personaje_murio( personaje, i, cantidad ); personaje_llego( cantidad, personaje, llegadas, i ); } } void movimiento_personajes( int* cantidad_personajes, personaje_t personaje[ MAX_PERSONAJES ] , char bando, int posicion_personaje, int* llegadas, char terreno[ MAX_TERRENO_FIL ][ MAX_TERRENO_COL ], int movimiento, int fila_llegada ){ for( int i=0; i<( *cantidad_personajes );i++ ){ if( personaje[ i ].codigo == HOMBRE ){ if( terreno[ personaje[ i ].fila+movimiento ][ personaje[ i ].columna ] == TERRENO_VACIO || terreno[ personaje[ i ].fila+movimiento ][ personaje[ i ].columna ] == ELFO ){ personaje[ i ].fila +=movimiento; } }else if( personaje[ i ].codigo == ORCO ){ if( terreno[ personaje[ i ].fila+movimiento ][ personaje[ i ].columna ] == TERRENO_VACIO || terreno[ personaje[ i ].fila+movimiento ][ personaje[ i ].columna ] == URUK ){ personaje[ i ].fila +=movimiento; } } } for( int i=0; i<( *cantidad_personajes ); i++ ){ if( personaje[ i ].fila == fila_llegada ){ eliminar_personaje( cantidad_personajes, personaje, llegadas ); } } } void inicializar_juego( juego_t* juego ){ juego->uruk.codigo = URUK; juego->elfos.codigo = ELFO; juego->hombres.codigo = HOMBRE; juego->orcos.codigo = ORCO; juego->cantidad_isengard = 0; juego->cantidad_rohan = 0; juego->turno_rohan = true; juego->turno_isengard = true; juego->llegadas_rohan = 0; juego->llegadas_isengard = 0; srand( ( unsigned )time( NULL ) ); cargar_mapa_inicial( juego->terreno ); printf( "Completar Datos para el JUGADOR 1.\n" ); perfil( &( juego )->j1.tipo, &( juego )->j1.intensidad ); if( juego->j1.tipo == ROHAN ){ juego->j2.tipo = ISENGARD; }else{ juego->j2.tipo = ROHAN; } juego->j2.intensidad = INTENSIDAD_MAX - juego->j1.intensidad; plus( juego->j1, juego ); plus( juego->j2, juego ); juego->j1.energia = ENERGIA_INICIAL; juego->j2.energia = ENERGIA_INICIAL; printf( "1-Jugador vs. CPU\n2-Jugador 1 vs. Jugador 2\n" ); scanf( "%i",&( juego->cant_jugadores ) ); system( "clear" ); inicializar_personajes_fijos( &( juego )->elfos, juego->plus_rohan ); inicializar_personajes_movibles( &( juego )->hombres, juego->plus_rohan ); inicializar_personajes_fijos( &( juego )->uruk, juego->plus_isengard ); inicializar_personajes_movibles( &( juego )->orcos, juego->plus_isengard ); posicionar_fijo_aleatorio( &( juego )->cantidad_isengard, juego->uruk, juego->terreno, juego->isengard, 1 ); posicionar_fijo_aleatorio( &( juego )->cantidad_rohan, juego->elfos, juego->terreno, juego->rohan, 5 ); } void posicionar_personaje( juego_t* juego, personaje_t personaje ){ if( personaje.codigo == HOMBRE ){ posicionar_moviles( ( *juego ).terreno, ULTIMA_FILA, juego->rohan, personaje, &( *juego ).cantidad_rohan, "ultima", "Hombre" ); } if( personaje.codigo == ORCO ){ posicionar_moviles( ( *juego ).terreno, PRIMER_FILA, juego->isengard, personaje, &( *juego ).cantidad_isengard, "primer", "Orco" ); } if( personaje.codigo == ELFO ){ posicionar_fijos( ( ULTIMA_FILA/2 )+1, ULTIMA_FILA-1, "( del 5 al 8 )", "Elfo", ( *juego ).terreno, ( *juego ).rohan, &( *juego ).cantidad_rohan, personaje ); } if( personaje.codigo == URUK ){ posicionar_fijos( PRIMER_FILA+1, ULTIMA_FILA/2, "( del 1 al 4 )", "Uruk-Hai", ( *juego ).terreno, ( *juego ).isengard, &( *juego ).cantidad_isengard, personaje ); } } void ataque_movibles( personaje_t vec_atacante[ MAX_PERSONAJES ], int cantidad_atacante, personaje_t vec_enemigos[ MAX_PERSONAJES ], int* cantidad_enemigos, char pers, char terreno[ MAX_TERRENO_FIL ][ MAX_TERRENO_COL ], int* llegadas_enemigos ){ for( int i=0; i < cantidad_atacante; i++ ){ if( vec_atacante[ i ].codigo == pers && vec_atacante[ i ].vida > 0 ){ for( int r=0; r < ( *cantidad_enemigos ); r++ ){ if( ( abs( vec_atacante[ i ].fila - vec_enemigos[ r ].fila ) + abs( vec_atacante[ i ].columna - vec_enemigos[ r ].columna ) )<=1 && vec_enemigos[ r ].vida > 0 ){ vec_enemigos[ r ].vida-=vec_atacante[ i ].ataque; if( vec_enemigos[ r ].vida<=0 ){ terreno[ vec_enemigos[ r ].fila ][ vec_enemigos[ r ].columna ]=TERRENO_VACIO; vec_enemigos[ r ].vida = 0; } }else if( ( vec_atacante[ i ].fila )-1 == vec_enemigos[ r ].fila && ( vec_atacante[ i ].columna )-1 == vec_enemigos[ r ].columna && ( ( vec_atacante[ i ].fila )-1 >= PRIMER_FILA ) && ( ( vec_atacante[ i ].columna )-1 >= PRIMER_COLUMNA ) ){ vec_enemigos[ r ].vida-=vec_atacante[ i ].ataque; if( vec_enemigos[ r ].vida<=0 ){ terreno[ vec_enemigos[ r ].fila ][ vec_enemigos[ r ].columna ]=TERRENO_VACIO; vec_enemigos[ r ].vida = 0; } }else if( ( vec_atacante[ i ].fila )-1 == vec_enemigos[ r ].fila && ( vec_atacante[ i ].columna )+1 == vec_enemigos[ r ].columna && ( ( vec_atacante[ i ].fila )-1 >= PRIMER_FILA ) && ( ( vec_atacante[ i ].columna )+1 <= ULTIMA_COLUMNA ) ){ vec_enemigos[ r ].vida-=vec_atacante[ i ].ataque; if( vec_enemigos[ r ].vida<=0 ){ terreno[ vec_enemigos[ r ].fila ][ vec_enemigos[ r ].columna ]=TERRENO_VACIO; vec_enemigos[ r ].vida = 0; } }else if( ( vec_atacante[ i ].fila )+1 == vec_enemigos[ r ].fila && ( vec_atacante[ i ].columna )-1 == vec_enemigos[ r ].columna && ( ( vec_atacante[ i ].fila )+1 <= ULTIMA_FILA ) && ( ( vec_atacante[ i ].columna )-1 >= PRIMER_COLUMNA ) ){ vec_enemigos[ r ].vida-=vec_atacante[ i ].ataque; if( vec_enemigos[ r ].vida<=0 ){ terreno[ vec_enemigos[ r ].fila ][ vec_enemigos[ r ].columna ]=TERRENO_VACIO; vec_enemigos[ r ].vida = 0; } }else if( ( vec_atacante[ i ].fila )+1 == vec_enemigos[ r ].fila && ( vec_atacante[ i ].columna )+1 == vec_enemigos[ r ].columna && ( ( vec_atacante[ i ].fila )+1 <= ULTIMA_FILA ) && ( ( vec_atacante[ i ].columna )+1 <= ULTIMA_COLUMNA ) ){ vec_enemigos[ r ].vida-=vec_atacante[ i ].ataque; if( vec_enemigos[ r ].vida<=0 ){ terreno[ vec_enemigos[ r ].fila ][ vec_enemigos[ r ].columna ]=TERRENO_VACIO; vec_enemigos[ r ].vida = 0; } } } } } for( int i=0; i < ( *cantidad_enemigos ); i++ ){ if( vec_enemigos[ i ].vida == 0 ){ eliminar_personaje( &( *cantidad_enemigos ), vec_enemigos, &( *llegadas_enemigos ) ); } } } void ataque_fijos( personaje_t vec_atacante[ MAX_PERSONAJES ], int cantidad_atacante, personaje_t vec_enemigos[ MAX_PERSONAJES ], int* cantidad_enemigos, char pers, int* llegadas_enemigo ){ for( int i=0; i < cantidad_atacante; i++ ){ if( vec_atacante[ i ].codigo == pers && vec_atacante[ i ].vida > 0 ){ for( int r=0; r < ( *cantidad_enemigos );r++ ){ if( ( abs( vec_atacante[ i ].fila - vec_enemigos[ r ].fila )+ abs( vec_atacante[ i ].columna - vec_enemigos[ r ].columna ) )<=3 && vec_enemigos[ r ].vida > 0 ){ vec_enemigos[ r ].vida-=vec_atacante[ i ].ataque; if( vec_enemigos[ r ].vida<=0 ){ vec_enemigos[ r ].vida = 0; } } } } } eliminar_personaje( cantidad_enemigos, vec_enemigos, llegadas_enemigo ); } void jugar( juego_t* juego, char bando, int posicion_personaje ){ if( bando == ISENGARD ){ movimiento_personajes( &( juego )->cantidad_isengard, juego->isengard, ISENGARD, juego->isengard->fila, &( juego )->llegadas_isengard, juego->terreno, 1, ULTIMA_FILA ); ataque_movibles( ( *juego ).isengard, ( *juego ).cantidad_isengard, ( *juego ).rohan, &( *juego ).cantidad_rohan, ORCO, ( *juego ).terreno, &( *juego ).llegadas_rohan ); ataque_fijos( ( *juego ).isengard, ( *juego ).cantidad_isengard, ( *juego ).rohan, &( *juego ).cantidad_rohan, ORCO, &( *juego ).llegadas_rohan ); }else{ movimiento_personajes( &( juego )->cantidad_rohan, juego->rohan, ROHAN, juego->rohan->fila, &( juego )->llegadas_rohan, juego->terreno, -1, PRIMER_FILA ); ataque_movibles( ( *juego ).rohan, ( *juego ).cantidad_rohan, ( *juego ).isengard, &( *juego ).cantidad_isengard, HOMBRE, ( *juego ).terreno, &( *juego ).llegadas_isengard ); ataque_fijos( ( *juego ).rohan, ( *juego ).cantidad_rohan, ( *juego ).isengard, &( *juego ).cantidad_isengard, HOMBRE, &( *juego ).llegadas_isengard ); } } void ganar( int llegadas, bool* juego_terminado, bool* turno_actual, bool* turno_enemigo, char bando[ 10 ] ){ if( llegadas == LLEGADAS_GANAR ){ ( *juego_terminado ) = true; ( *turno_actual )=false; ( *turno_enemigo ) = false; system( "clear" ); printf( "\n%s Gana!!!\n", bando ); } } void aumentar_energia( jugador_t* j1, jugador_t* j2 ){ ( *j1 ).energia++; ( *j2 ).energia++; if( ( *j1 ).energia > ENERGIA_MAX ){ ( *j1 ).energia = ENERGIA_MAX; } if( ( *j2 ).energia > ENERGIA_MAX ){ ( *j2 ).energia = ENERGIA_MAX; } } void turno( bool* turno_actual, char bando, juego_t* juego, char str_bando[ 10 ], int* llegadas_bando, char str_pers_movible[ 8 ], char str_pers_fijo[ 10 ], personaje_t personaje_movible, personaje_t personaje_fijo, bool* turno_enemigo, personaje_t vec_actual[ MAX_PERSONAJES ], bool* juego_terminado ){ char rta_bando; int crear_pers; while( ( *turno_actual ) ){ system( "clear" ); if( juego->j1.tipo == bando ){ cargar_mapa_inicial( juego->terreno ); cargar_personajes( juego ); actualizar_terreno( juego ); printf( "Energia %s: %i\n",str_bando, juego->j1.energia ); printf( "Llegadas %s: %i",str_bando, ( *llegadas_bando ) ); printf( "\n\t\tTURNO %s.\nDesea crear un personaje?.( S/N ).\n", str_bando ); scanf( " %c", &rta_bando ); rta_bando = toupper( rta_bando ); validar_respuesta_crear( &rta_bando ); if( rta_bando == 'S' ){ printf( "Que personaje desea crear?.\n1-%s.( 3pts. de energia )\n2-%s.( 8pts. de energia )\n", str_pers_movible, str_pers_fijo ); scanf( "%i", &crear_pers ); while( crear_pers !=1 && crear_pers !=2 ){ printf( "ERROR. Ingrese una opcion valida.\n1-%s.( 3pts. de energia )\n2-%s.( 8pts. de energia )\n", str_pers_movible, str_pers_fijo ); scanf( "%i", &crear_pers ); } if( crear_pers == 1 ){ if( juego->j1.energia >= personaje_movible.pts_energia ){ posicionar_personaje( juego, personaje_movible ); juego->j1.energia -= personaje_movible.pts_energia; }else{ printf( "\nNo tiene puntos suficientes para crear a un %s.\n", str_pers_movible ); } }else{ if( juego->j1.energia >= personaje_fijo.pts_energia ){ posicionar_personaje( juego, personaje_fijo ); juego->j1.energia -= personaje_fijo.pts_energia; }else{ printf( "\nNo tiene puntos suficientes para crear a un %s.\n", str_pers_fijo ); } } }else{ ( *turno_actual ) = false; ( *turno_enemigo ) = true; } }else if( juego->j2.tipo == bando ){ cargar_mapa_inicial( juego->terreno ); cargar_personajes( juego ); actualizar_terreno( juego ); printf( "Energia %s: %i\n",str_bando, juego->j2.energia ); printf( "Llegadas %s: %i", str_bando, ( *llegadas_bando ) ); printf( "\n\t\tTURNO %s.\nDesea crear un personaje?.( S/N ).\n", str_bando ); scanf( " %c", &rta_bando ); rta_bando = toupper( rta_bando ); validar_respuesta_crear( &rta_bando ); if( rta_bando == 'S' ){ printf( "Que personaje desea crear?.\n1-%s.( 3pts. de energia )\n2-%s.( 8pts. de energia )\n", str_pers_movible, str_pers_fijo ); scanf( "%i", &crear_pers ); while( crear_pers !=1 && crear_pers !=2 ){ printf( "ERROR. Ingrese una opcion valida.\n1-%s.( 3pts. de energia )\n2-%s.( 8pts. de energia )\n", str_pers_movible, str_pers_fijo ); scanf( "%i", &crear_pers ); } if( crear_pers == 1 ){ if( juego->j2.energia >= personaje_movible.pts_energia ){ posicionar_personaje( juego, personaje_movible ); juego->j2.energia -= personaje_movible.pts_energia; }else{ printf( "No tiene puntos suficientes para crear a un %s.\n", str_pers_movible ); } }else{ if( juego->j2.energia >= personaje_fijo.pts_energia ){ posicionar_personaje( juego, personaje_fijo ); juego->j2.energia -= personaje_fijo.pts_energia; }else{ printf( "No tiene puntos suficientes para crear a un %s.\n", str_pers_fijo ); } } }else{ ( *turno_actual ) = false; ( *turno_enemigo ) = true; } } } jugar( juego, bando, vec_actual->fila ); ganar( ( *llegadas_bando ), juego_terminado, &( *turno_actual ), &( *turno_enemigo ), str_bando ); } void turno_vs_cpu( bool* turno_actual, char bando, juego_t* juego, char str_bando[ 10 ], int* llegadas_bando, char str_pers_movible[ 8 ], char str_pers_fijo[ 10 ], personaje_t personaje_movible, personaje_t personaje_fijo, bool* turno_enemigo, personaje_t vec_actual[ MAX_PERSONAJES ],int* cantidad_aliado, bool* juego_terminado, int fila_inicial ){ int crear_pers; char rta_bando; while( ( *turno_actual ) ){ system( "clear" ); if( juego->j1.tipo == bando ){ cargar_mapa_inicial( juego->terreno ); cargar_personajes( juego ); actualizar_terreno( juego ); printf( "Energia %s: %i\n",str_bando, juego->j1.energia ); printf( "Llegadas %s: %i",str_bando, ( *llegadas_bando ) ); printf( "\n\t\tTURNO %s.\nDesea crear un personaje?.( S/N ).\n", str_bando ); scanf( " %c", &rta_bando ); rta_bando = toupper( rta_bando ); validar_respuesta_crear( &rta_bando ); if( rta_bando == 'S' ){ printf( "Que personaje desea crear?.\n1-%s.( 3pts. de energia )\n2-%s.( 8pts. de energia )\n", str_pers_movible, str_pers_fijo ); scanf( "%i", &crear_pers ); while( crear_pers !=1 && crear_pers !=2 ){ printf( "ERROR. Ingrese una opcion valida.\n1-%s.( 3pts. de energia )\n2-%s.( 8pts. de energia )\n",str_pers_movible, str_pers_fijo ); scanf( "%i", &crear_pers ); } if( crear_pers == 1 ){ if( juego->j1.energia >= personaje_movible.pts_energia ){ posicionar_personaje( juego, personaje_movible ); juego->j1.energia -= personaje_movible.pts_energia; }else{ printf( "\nNo tiene puntos suficientes para crear a un %s.\n", str_pers_movible ); } }else{ if( juego->j1.energia >= personaje_fijo.pts_energia ){ posicionar_personaje( juego, personaje_fijo ); juego->j1.energia -= personaje_fijo.pts_energia; }else{ printf( "\nNo tiene puntos suficientes para crear a un %s.\n", str_pers_fijo ); } } }else{ ( *turno_actual ) = false; ( *turno_enemigo ) = true; } }else if( juego->j2.tipo == bando ){ cargar_mapa_inicial( juego->terreno ); cargar_personajes( juego ); actualizar_terreno( juego ); printf( "\nEnergia %s: %i\n",str_bando, juego->j2.energia ); printf( "\nLlegadas %s: %i\n",str_bando, juego->llegadas_rohan ); printf( "\n\t\tTURNO %s.\n", str_bando ); if( juego->j2.energia >= personaje_movible.pts_energia ){ posicionar_movil_aleatorio( cantidad_aliado, personaje_movible, juego->terreno, vec_actual, &( *juego ).j2, fila_inicial ); }else{ printf( "\nNo tiene puntos suficientes para crear a un %s.\n", str_pers_movible ); } ( *turno_actual ) = false; ( *turno_enemigo ) = true; } } jugar( juego, bando, vec_actual->fila ); ganar( ( *llegadas_bando ), juego_terminado, turno_actual, turno_enemigo, str_bando ); }
C
/******************************************************************* ** Lcd.h * * DESCRIPTION: LCD.c module header file * * AUTHOR: Todd Morton * * HISTORY: 01/23/2013 * ********************************************************************* * WWULCD Function prototypes * ********************************************************************/ extern void LcdInit(void); /* Initializes display. Takes */ /* ~15ms to run */ extern void LcdClrDisp(void); /* Clears display and returns */ /* cursor to (1,1) */ /* Takes >2ms */ extern void LcdClrLine(INT8U line); /* Clears line. Legal line */ /* numbers are 1 and 2. */ /* Takes > 850us */ extern void LcdDispChar(INT8U c); /* Displays ASCII character, c */ /* Takes ~50us */ extern void LcdDispByte(INT8U *b); /* Displays byte, b, in hex */ /* Takes ~50us */ extern void LcdDispStrg(INT8U *s); /* Displays string pointed to */ /* by *s. Note, that the string*/ /* must fit on the line. (i.e. */ /* no provision is made for */ /* wrapping. */ /* Takes 50us times the string */ /* length. */ extern void LcdMoveCursor(INT8U row, INT8U col); /* Moves cursor to*/ /* row row and col column. row */ /* can be 1 or 2. col can be 1 */ /* through 16. */ /* Takes ~50us */ extern void LcdDispDecByte(INT8U *b, INT8U lz); /* Displays the */ /* byte pointed to by *b in */ /* decimal. If lz is one, */ /* leading zeros are displayed.*/ /* If lz is 0, leading zeros */ /* are not displayed but digits*/ /* remain right justified. */ /* Takes <150us */ extern void LcdDispTime(INT8U hrs, INT8U mins, INT8U secs); /* Displays hrs:mins:secs */ /* Each is displayed as 2 */ /* decimal digits. */ /* Take ~400us */ extern void LcdCursor(INT8U on, INT8U blink); /* Configures cursor */ /* If on is TRUE cursor is on. */ /* If blink is TRUE, the cursor*/ /* blinks. */ /* Takes ~50us */ extern void LcdBSpace(void); /* move cursor left one space */ extern void LcdFSpace(void); /* move cursor right one space */ /********************************************************************/
C
#include <stdio.h> #include <string.h> char buf[100000], a[128][1000]; int isdig(int c) { return c >= '0' && c <= '9'; } int main() { int cas, count, n, i, temp; char *ptr; cas = 0; for(i=0; i<=127; i++) { memset(a[i], i, sizeof(a[i])); } gets(buf); sscanf(buf, "%d", &count); while(count--) { printf("Case %d: ", ++cas); gets(buf); for(ptr=buf; *ptr; ) { temp = *ptr; for(n=0, ptr++; *ptr&&isdig(*ptr); n*=10, n+=*ptr-'0', ptr++); printf("%.*s", n, a[temp]); } putchar('\n'); } return 0; }
C
#include <stdio.h> #include <stdint.h> #include <string.h> #include "mindless_machine.h" #include "graphio.h" struct graph { size_t size_graph; char** v_graph; double** e_graph; } graph; int read_string (char *str) { char s = ' '; int n = 0; if (str == NULL) { return -2; } while (s != '\n') { scanf("%c", &s); *(str + n) = s; ++n; } --n; *(str + n) = '\0'; return n; } int write_console(char const *str) { const char *cur = str; if (str == NULL) { return -1; } while (*cur != '\0') { printf("%c", *cur); ++cur; } return 0; } int write_file(char const *fname, char const *str){ const char *cur = str; FILE *f = fopen(fname, "w+"); if (str == NULL) { return -1; } while (*cur != '\0') { fprintf(f, "%c", *cur); ++cur; } return(0); } int create_machine(char *str, struct graph *graph){ if (str == NULL || graph == NULL){ return -1; } str_to_down(str); str = str_replace_punct(str); char* str_prev = "."; str = strtok (str, " \n"); while (str != NULL) { graph_add_e_graph(str_prev, str, graph); str_prev = str; str = strtok (NULL, " "); } graph->e_graph[0][0] = 0; graph_to_probability(graph); return 0; } bool str_to_down(char* str){ if (str == NULL){ return false; } char* cur = str; while (*cur != '\0'){ if (*cur >= (char)'A' && *cur <= (char)'Z'){ *cur = (*cur - (char)'A') + (char)'a'; } ++cur; } return true; } char* str_replace_punct(char* str){ char* res_str = (char*)malloc(2 * strlen(str) * sizeof(char)); //результирующая строка может быть максимум в 2 раа больше char* cur_str = str; char* cur_res = res_str; while(*cur_str != '\0'){ if (find_char_in_template(*cur_str, "\"\r\n\t")){ ++cur_str; *cur_res = ' '; ++cur_res; continue; } if (!find_char_in_template(*cur_str, " \'") && !char_in_interval(*cur_str, 'a', 'z') && !char_in_interval(*cur_str, 'A', 'Z') && !char_in_interval(*cur_str, '0', '9')){ *cur_res = ' '; ++cur_res; } *cur_res = *cur_str; ++cur_res; if (*cur_str == '-'){ *cur_res = ' '; ++cur_res; } ++cur_str; } *cur_res = '\0'; free(str); return res_str; } struct graph* graph_create(size_t sz) { struct graph *gr = (struct graph *) malloc(sizeof(gr)); gr->size_graph = 0; gr->v_graph = (char **) malloc(sz * sizeof(char *)); for (size_t i = 0; i < sz; ++i) { gr->v_graph[i] = (char *) malloc(sizeof(char) * 256); } gr->e_graph = (double **) malloc(sz * sizeof(double *)); for (size_t i = 0; i < sz; ++i) { gr->e_graph[i] = (double *) malloc(sz * sizeof(double)); for (size_t j = 0; j < sz; ++j) { gr->e_graph[i][j] = 0; } } return gr; } int graph_search_elem(char const *str, struct graph const* graph){ if (str == NULL || graph == NULL){ return -2; } for (size_t i = 0; i < graph->size_graph; ++i){ if (strcmp(graph->v_graph[i], str) == 0){ return (int)i; } } return -1; } int graph_add_v_graph(char const *str, struct graph* graph){ if (str == NULL || graph == NULL){ return -1; } int s = graph_search_elem(str, graph); if (s != -1){ return s; } ++(graph->size_graph); graph->v_graph[graph->size_graph - 1] = (char*)str; return (int)graph->size_graph - 1; } int graph_add_e_graph(char const *str_prev, char const *str_cur, struct graph* graph){ if(str_cur == NULL || str_prev == NULL || graph == NULL){ return -1; } int i, j; i = graph_add_v_graph(str_prev, graph); j = graph_add_v_graph(str_cur, graph); ++(graph->e_graph[i][j]); return 0; } bool save_graph(FILE *output_file, struct graph const* graph){ if (output_file == NULL){ return false; } fprintf(output_file, "%lu\n", graph->size_graph); for (size_t i = 0; i < graph->size_graph; ++i){ fprintf(output_file, "%s\n", graph->v_graph[i]); } for(size_t i = 0; i < graph->size_graph; ++i){ for (size_t j = 0; j < graph->size_graph; ++j){ fprintf(output_file, "%lf ", graph->e_graph[i][j]); } fprintf(output_file, "\n"); } fclose(output_file); return true; } struct graph* load_graph(FILE *input_file){ if (input_file == NULL){ return NULL; } size_t sz; if (fscanf(input_file, "%lu", &sz) != 1){ return NULL; } struct graph* graph = graph_create(sz); graph->size_graph = sz; for (size_t i = 0; i < sz; ++i){ fscanf(input_file, "%s", graph->v_graph[i]); } for (size_t i = 0; i < sz; ++i){ for (size_t j = 0; j < sz; ++j){ if (fscanf(input_file, "%lf", &graph->e_graph[i][j]) == EOF) { return NULL; } } } fclose(input_file); return graph; } bool graph_to_probability(struct graph *graph){ if (graph == NULL){ return false; } for (size_t i = 0; i < graph->size_graph; ++i) { graph->e_graph[i][i] = 0; } for (size_t i = 0; i < graph->size_graph; ++i){ double sum = 0; for(size_t j = 0; j < graph->size_graph; ++j){ sum += graph->e_graph[i][j]; } if (sum == 0){ graph->e_graph[i][0] = 1; sum = 1; } for(size_t j= 0; j < graph->size_graph; ++j){ graph->e_graph[i][j] = graph->e_graph[i][j] / sum + ((j == 0)? 0 : graph->e_graph[i][j - 1]); } } return true; } bool find_char_in_template(char c, char const *template){ if (template == NULL){ return false; } const char *cur = template; while (*cur != '\0') { if (c == *cur){ return true; } ++cur; } return false; } bool char_in_interval(char c, char start, char end){ if (c >= start && c <= end){ return true; } return false; }
C
#include <signal.h> #include <stdio.h> #include <stdlib.h> #include <time.h> static void catch_function(int signal) { int n = 0; printf("Enter the number\n"); scanf("%d",&n); } int main(void) { time_t start,end; double diff = 0.00; printf("hello all\n"); do { start = time(NULL); if(signal(SIGINT, catch_function) !=SIG_ERR); raise(SIGINT); end = time(NULL); diff = diff + difftime(end,start); if(diff >= 10) { int c; printf("time duration exceed \n do you want to continue enter \n1-continue\n2-exit\n"); scanf("%d",&c); if(c == 1) { diff = 0; signal(SIGINT,catch_function); raise(SIGINT); } else { exit(0); } } printf("%lf\n",diff); }while(diff <= 60.0); return 0; }
C
/* * test_bind.c * * Created on: Jun 20, 2014 * Author: Ali Gholami */ #include "testcases.h" int main(int argc, char **argv) { test_bind(); return 0; } void test_bind( ) { int sockfd; struct sockaddr_in dest; /* open a streaming socket */ if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { fprintf(stderr, "Socket error %d \n", sockfd); return; } /* initalize the socket structure */ dest.sin_family = AF_INET; dest.sin_port = htons(BIND_SERVER_PORT); dest.sin_addr.s_addr = INADDR_ANY; bzero( &dest, sizeof(dest)); int ret; if ((ret = bind(sockfd, (struct sockaddr *) &dest, sizeof(dest)) < 0)){ fprintf(stderr, "binding error \n"); return; } if (close(sockfd)!= 0){ fprintf(stderr, "close() error \n"); return; } fprintf(stdout, "bind() successfully %d \n", ret); }
C
#include <shell.h> #include <interprete.h> #include <builtins.h> #include <string.h> #include <stdio.h> t_env *init_env(void) { t_env *env; if (!(env = (t_env *)debug_malloc(sizeof(t_env)))) return (ERROR); /* Old was 65536 */ env->local_variables = ht_create( 8192 ); env->alias = ht_create( 8192 ); env->builtins = ht_create( 8192 ); env->binaries = ht_create( 8192 ); env->intro = strdup(SHELL_NAME"> "); init_builtins(env->builtins); if (!(env->interpretation = init_interpretation())) { free(env); return (ERROR); } memcpy(env->pwd, "<PWD VALUE>", sizeof(env->pwd)); memcpy(env->home, "<HOME VALUE>", sizeof(env->home)); env->pwd_len = strlen(env->pwd); env->home_len = strlen(env->home); env->interpretation->pwd = env->pwd; env->interpretation->pwd_len = env->pwd_len; env->interpretation->home = env->home; env->interpretation->home_len = env->home_len; return (env); } void free_argv(t_env *env) { size_t id; id = 0; while (id < env->interpretation->argv_pool_size) { // printf("Free of [%s]\n", env->argv_pool[id]); free(env->interpretation->argv_pool[id++]); } env->interpretation->argv_pool_size = 0; } void add_local_variable(t_env *env, const char *key, const char *value) { ht_set(env->local_variables, strdup(key), strdup(value)); } void *debug_malloc(size_t size) { // printf("\t\t<MALLOC>\n\t\tRequested a malloc of %lu\n\n", size); return (malloc(size)); } #include <unistd.h> int get_line(const char *intro, char *buffer, size_t size) { write(1, intro, strlen(intro)); return (read(1, buffer, size)); } void subshell(t_env *env, ssize_t *size) { ssize_t tmp; env->multiline = 1; if (env->interpretation->last_char == SIMPLE_QUOTED) write(1, "quote> ", 7); else if (env->interpretation->last_char == DOUBLE_QUOTED) write(1, "dquote> ", 8); else if (env->interpretation->last_char == BACK_QUOTED) write(1, "bquote> ", 8); else if (env->interpretation->last_char == BACKSLASHED) write(1, "> ", 2); else { write(1, "UNKNOWN ERROR WTF\n", 18); exit (ERROR_EXIT); } if ((tmp = get_line("", env->line + *size, sizeof(env->line) - *size)) < 0) { write(1, "Read error\n", 11); exit (ERROR_EXIT); } *size += tmp; env->interpretation->len = *size; } void update_interpretation(t_env *env) { env->interpretation->local_variables = env->local_variables; env->interpretation->alias = env->alias; env->interpretation->builtins = env->builtins; env->interpretation->binaries = env->binaries; memcpy(env->interpretation->line, env->line, sizeof(env->interpretation->line)); } int main(void) { t_env *env; ssize_t size; if ((env = init_env()) == ERROR) return (ERROR_EXIT); env->interpretation->start = 0; add_local_variable(env, "HOME", "/nfs/zfs-student-3/users/2014/achazal"); add_local_variable(env, "PWD", "/nfs/zfs-student-3/users/2014/achazal/tutoSh1/escaping"); add_local_variable(env, "PATH", "/nfs/zfs-student-3/users/2014/achazal/.brew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/texbin"); while ((size = get_line(env->intro, env->line, sizeof(env->line))) > 0) { env->multiline = 0; env->line[sizeof(env->line) - 1] = '\0'; env->interpretation->len = size - 1; update_interpretation(env); env->interpretation->len = size - 1; while (start_interprete(env->interpretation) == NOT_CLOSED) subshell(env, &size); if (env->multiline) --env->interpretation->len; if (env->interpretation->len) launch_command(env); } // ht_free(env->alias); // ht_free(env->local_variables); // ht_free(env->builtins); // ht_free(env->binaries); free(env); return (NORMAL_EXIT); }
C
#ifndef AFFICHAGES_H #define AFFICHAGES_H #include <math.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "projet.h" void print_tab_BYTE(BYTE *tab, size_t len) { for (size_t i = 0; i < len; ++i) { printf("{"); for (size_t j = 0; j < 8; ++j) { printf("%d", (tab[i] >> (7 - j)) & 1); } printf("} "); } printf("\n\n"); } void print_tab(BYTE *tab, size_t len) { for (size_t i = 0; i < len; ++i) { if(i%8==0) printf("\n"); printf("%2d ", tab[i]); } printf("\n\n"); } void print_tab_int(int *tab, size_t len) { for (size_t i = 0; i < len; ++i) { printf("%d ", tab[i]); } printf("\n\n"); } void print_byte_binary(BYTE x) { for (int i = 7; i >= 0; i--) { printf("%d", (x >> i) & 1 ? 1 : 0); } } void print_tab_binary(BYTE *tab, size_t len) { for (size_t i = 0; i < len; ++i) { print_byte_binary(tab[i]); printf(" "); } printf("\n"); } void print_tab_hex(BYTE *tab, size_t len) { for (size_t i = 0; i < len; ++i) { printf("%x", tab[i]); printf(" "); } printf("\n"); } void print_tab_tab(BYTE tab[16][48]) { printf("\n"); for (int i = 0; i < 16; ++i) { for (int j = 0; j < 48; ++j) { printf("%d ", tab[i][j]); } printf("\n"); } printf("\n\n"); } void print_tab_tab_hex(BYTE (*tab)[48], int rounds) { printf("\n"); BYTE res[48]; for (int i = 0; i < rounds; ++i) { pack8(res, tab[i]); print_tab_hex(res, 6); } printf("\n\n"); } #endif //AFFICHAGES_H
C
#include <stdio.h> #include <string.h> #include <ctype.h> #define LEXEME_COUNT 26 // Number of members in cifLexemes #define CIF_RESULT_FILENAME "cif_result.txt" char * get_arguments(int argc, char * argv[]) { return (argc > 1) ? argv[1] : NULL; // Return the cifFileName of NULL } char * get_cif_lex_value(char * inputStr) { char * str = inputStr; while( *str && !isspace( (unsigned char) * str) ) ++str; // Ignore lexeme like _cell_length_a while( *str && isspace( (unsigned char) * str) ) ++str; // Ignore spaces after lexeme before its value return str; } void write_data(FILE * file1, FILE * file2, char * lexeme, char * value) { fprintf(file1, "%s", value); // Write lexValue to CIF_RESULT_FILENAME fprintf(file2, "%35s\t%s", lexeme, value); // Write data to command line } void read_cif_file(char * cifFileName) { FILE * cifFile = fopen(cifFileName, "r"); FILE * outFile = fopen(CIF_RESULT_FILENAME, "w"); char str[128]; char * lexValue = ""; char *cifLexemes[] = { "_chemical_formula_moiety", //string like 'C24 H22 F3 N O3' "_chemical_formula_weight", //float, like 429.42 "_cell_measurement_temperature", //int like 120 "_space_group_crystal_system", //string like 'monoclinic' "_space_group_name_H-M_alt", // string like 'P 1 21/c 1' => P21/c "_cell_formula_units_Z", // int like 4 or float ??? "_cell_length_a", //string like 13.9693(14) "_cell_length_b", //string like 16.7422(15) "_cell_length_c", //string like 9.3739(8) "_cell_angle_alpha", //string like 90 or float 103.524(2) "_cell_angle_beta", //string like 90 or float 103.524(2) "_cell_angle_gamma", //string like 90 or float 103.524(2) "_cell_volume", //string like 2131.5(3) "_exptl_crystal_density_diffrn", //float like 1.338 "_exptl_absorpt_coefficient_mu", //float like 0.105 "_exptl_crystal_F_000", //int like 896 "_2thetha", //int like 56 "_diffrn_reflns_number", //int like 19309 "_reflns_number_total", //int like 6507 "_reflns_number_gt", //int like 3852 "_refine_ls_number_parameters", //int like 310 "_refine_ls_R_factor_all", //float like 0.1064 "_refine_ls_wR_factor_gt", //float like 0.1147 "_refine_ls_restrained_S_all", //float like 1.013 "_refine_diff_density_max", //float like 0.317 "_refine_diff_density_min" //float like -0.280 }; if (cifFile) { for (int i = 0; i < LEXEME_COUNT; i++) { lexValue = ""; while(!feof(cifFile)) { if (fgets(str, 127, cifFile)) if ( strncmp(cifLexemes[i], str, strlen(cifLexemes[i])) == 0 ) // Found the lexeme in cifFile { lexValue = get_cif_lex_value(str); write_data(outFile, stdout, cifLexemes[i], lexValue); } } if (strcmp(lexValue, "") == 0) write_data(outFile, stdout, cifLexemes[i], "!No value!\n"); fseek(cifFile, 0, SEEK_SET); // Start from the beginning of cifFile } } else { fprintf(outFile, "Error! No CIF file!\n"); } fclose(cifFile); fclose(outFile); } int main(int argc, char * argv[]) { char * cifFileName = get_arguments(argc, argv); read_cif_file(cifFileName); return 0; }
C
//References used: UNIX Programming Textbook AND several youtube videos (can provide list and urls if necessary) #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <signal.h> #include <errno.h> #include <sys/shm.h> char slave_id[3]; int sharedmemid_sharedNum; //Shared memory segment id #global int* sharedNum; //pointer to shared memory of #global key_t key_sharedNum = 9823; //shared memory segment int sharedmemid_sharedGlobal; //holds the shared memory segment id #global int* sharedGlobal; //pointer of shared int variables #global key_t key_sharedGlobal = 9824; //shared memory segment //slave process handler void signalCallback (int signum) { printf("\nSIGTERM from slave %d\n", atoi(slave_id)); // Cleanup the shared memory allocated shmdt(sharedNum); shmdt(sharedGlobal); exit(0); } int main(int argc, char* argv[]) { strcpy(slave_id, argv[1]); if (signal(SIGTERM, signalCallback) == SIG_ERR) { perror("Error: slave: signal().\n"); exit(errno); } //master assigns shared memory segment if ((sharedmemid_sharedNum = shmget(key_sharedNum, sizeof(int), 0600)) < 0) { perror("Error: sharedmem_get"); exit(errno); } //attach the shared memory sharedNum = shmat(sharedmemid_sharedNum, NULL, 0); //master process assigns second shared memory segment if ((sharedmemid_sharedGlobal = shmget(key_sharedGlobal, sizeof(int) * (*sharedNum +1), IPC_CREAT | 0600)) < 0) { perror("Error: sharedmem_get"); exit(errno); } //attach shared memory to sharedGlobal sharedGlobal = shmat(sharedmemid_sharedGlobal, NULL, 0); int i; for(i = 0; i <= *sharedNum; i++) { sharedGlobal[i] = i; } printf("%s %d array size = %d\n\tarray value = %d\n",argv[0], atoi(slave_id), *sharedNum, sharedGlobal[atoi(slave_id)]); sleep(3); //Clean up shared memory shmdt(sharedNum); shmdt(sharedGlobal); return 0; }
C
/* ------------------------------------------- Name: Edward Vuong Student number: 120246186 Email: [email protected] Section: SII Date: July 31, 2018 ---------------------------------------------- Assignment: 2 Milestone: 4 ---------------------------------------------- */ #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> // +-------------------------------------------------+ // | NOTE: Include additional header files... | // +-------------------------------------------------+ #include "contacts.h" #include "contactHelpers.h" // +-------------------------------------------------+ // | NOTE: Copy/Paste your Assignment-2 Milestone-3 | // | source code below... | // +-------------------------------------------------+ // getName: void getName (struct Name* names) { printf("Please enter the contact's first name: "); scanf(" %[^\n]", names->firstName); printf("Do you want to enter a middle initial(s)? (y or n): "); clearKeyboard(); if (yes() == 1) { printf("Please enter the contact's middle initial(s): "); scanf("%s", names->middleInitial); } printf("Please enter the contact's last name: "); scanf(" %[^\n]", names->lastName); } // getAddress: void getAddress (struct Address* address) { printf("Please enter the contact's street number: "); address->streetNumber = getInt(); printf("Please enter the contact's street name: "); scanf(" %[^\n]", address->street); clearKeyboard(); printf("Do you want to enter an apartment number? (y or n): "); if (yes() == 1) { printf("Please enter the contact's apartment number: "); address->apartmentNumber = getInt(); } printf("Please enter the contact's postal code: "); scanf(" %[^\n]", address->postalCode); clearKeyboard(); printf("Please enter the contact's city: "); scanf(" %[^\n]", address->city); } // getNumbers: // HINT: Update this function to use the new helper // function "getTenDigitPhone" where applicable void getNumbers (struct Numbers* numbers){ printf("Please enter the contact's cell phone number: "); getTenDigitPhone(numbers->cell); printf("Do you want to enter a home phone number? (y or n): "); if (yes() == 1) { printf("Please enter the contact's home phone number: "); getTenDigitPhone(numbers->home); } else { strcpy(numbers->home, "\0"); } printf("Do you want to enter a business phone number? (y or n): "); if (yes() == 1) { printf("Please enter the contact's business phone number: "); getTenDigitPhone(numbers->business); } else { strcpy(numbers->business, "\0"); } } // getContact void getContact (struct Contact* contact) { getName(&contact->name); getAddress(&contact->address); getNumbers(&contact->numbers); }
C
/******************************* ** commonHeader.c ** ** Chieh-An Lin ** ** Version 2015.02.25 ** *******************************/ #include "commonHeader.h" //---------------------------------------------------------------------- //-- Functions related to int_arr int_arr *initialize_int_arr(int length) { int_arr *iArr = (int_arr*)malloc(sizeof(int_arr)); iArr->length = length; iArr->array = (int*)calloc(length, sizeof(int)); return iArr; } void free_int_arr(int_arr *iArr) { if (iArr->array) {free(iArr->array); iArr->array = NULL;} free(iArr); iArr = NULL; return; } void print_int_arr(int_arr *iArr) { printf("# int_arr\n"); int L = (int)fmin(iArr->length, 20); int i; for (i=0; i<L; i++) printf(" %d ", iArr->array[i]); printf("\n"); return; } //---------------------------------------------------------------------- //-- Functions related to double_arr double_arr *initialize_double_arr(int length) { double_arr *fArr = (double_arr*)malloc(sizeof(double_arr)); fArr->length = length; fArr->array = (double*)calloc(length, sizeof(double)); return fArr; } void free_double_arr(double_arr *fArr) { if (fArr->array) {free(fArr->array); fArr->array = NULL;} free(fArr); fArr = NULL; return; } void print_double_arr(double_arr *fArr) { printf("# double_arr\n"); int L = (int)fmin(fArr->length, 20); int i; for (i=0; i<L; i++) printf(" %.3f ", fArr->array[i]); printf("\n"); return; } //---------------------------------------------------------------------- //-- Functions related to double_mat double_mat *initialize_double_mat(int N1, int N2) { double_mat *fMat = (double_mat*)malloc(sizeof(double_mat)); fMat->N1 = N1; fMat->N2 = N2; fMat->length = N1 * N2; fMat->matrix = (double*)calloc(fMat->length, sizeof(double)); return fMat; } void free_double_mat(double_mat *fMat) { if (fMat->matrix) {free(fMat->matrix); fMat->matrix = NULL;} free(fMat); fMat = NULL; return; } void print_double_mat(double_mat *fMat) { printf("# double_mat\n"); int L1 = (int)fmin(fMat->N1, 8); int L2 = (int)fmin(fMat->N2, 8); int i, j; for (j=0; j<L2; j++) { for (i=0; i<L1; i++) { printf(" %9g ", fMat->matrix[i+j*fMat->N1]); } printf("\n"); } return; } //---------------------------------------------------------------------- //-- Functions related to double_ten3 double_ten3 *initialize_double_ten3(int N1, int N2, int N3) { double_ten3 *fTen = (double_ten3*)malloc(sizeof(double_ten3)); fTen->N1 = N1; fTen->N2 = N2; fTen->N3 = N3; fTen->length = N1 * N2 * N3; fTen->tensor = (double*)calloc(fTen->length, sizeof(double)); return fTen; } void free_double_ten3(double_ten3 *fTen) { if (fTen->tensor) {free(fTen->tensor); fTen->tensor = NULL;} free(fTen); fTen = NULL; return; } //---------------------------------------------------------------------- //-- Functions related to interpolator_t interpolator_t *initialize_interpolator_t(int length) { //-- length = number of points //-- dx = interval width //-- *x = coordinate //-- *value = value interpolator_t *inter = (interpolator_t*)malloc(sizeof(interpolator_t)); inter->length = length; inter->dx = 0.0; inter->x = (double*)calloc(length, sizeof(double)); inter->value = (double*)calloc(length, sizeof(double)); return inter; } void free_interpolator_t(interpolator_t *inter) { if (inter->x) {free(inter->x); inter->x = NULL;} if (inter->value) {free(inter->value); inter->value = NULL;} free(inter); inter = NULL; return; } void print_interpolator_t(interpolator_t *inter) { printf("# interpolator_t\n"); printf("# Number of points = %d\n", inter->length); printf("# Interval = %g\n", inter->dx); printf("#\n"); printf("# x value\n"); int i; for (i=0; i<inter->length; i++) printf(" %9g %9g\n", inter->x[i], inter->value[i]); return; } double execute_interpolator_t(interpolator_t *inter, double x) { int length = inter->length; double *coor = inter->x; double *value = inter->value; if (x > coor[length-1] || x < coor[0]) { printf("Value out of range of interpolator\n"); exit(1); } int i; for (i=1; i<length; i++) { if (coor[i] >= x) break; } double r = (x - coor[i-1]) / (coor[i] - coor[i-1]); return (1-r)*value[i-1] + r*value[i]; } //---------------------------------------------------------------------- //-- Functions related to sampler_t sampler_t *initialize_sampler_t(int length) { //-- length = number of points //-- dx = interval width //-- *x = bin values //-- *pdf = normalized pdf //-- *cdf = normalized cdf //-- totPdf = integration over pdf, before or after normalization (see set_sampler_t) //-- x_mean = integration over x*p(x), before or after normalization (see set_sampler_t) //-- //-- Usage: //-- - initialize it with length //-- - fill dx, x[0], rest of x //-- - fill pdf (not necessarily normalized) //-- - use set_sampler_t to set sampler_t *samp = (sampler_t*)malloc(sizeof(sampler_t)); samp->length = length; samp->x = (double*)calloc(length, sizeof(double)); samp->pdf = (double*)calloc(length, sizeof(double)); samp->cdf = (double*)calloc(length, sizeof(double)); samp->x_mean = 0; return samp; } void free_sampler_t(sampler_t *samp) { if (samp->x) {free(samp->x); samp->x = NULL;} if (samp->pdf) {free(samp->pdf); samp->pdf = NULL;} if (samp->cdf) {free(samp->cdf); samp->cdf = NULL;} free(samp); samp = NULL; return; } void print_sampler_t(sampler_t *samp) { printf("# sampler_t\n"); int L = (int)fmin(samp->length, 20); int i; printf("# length = %d\n", samp->length); printf("# dx = %g\n", samp->dx); printf("# x ="); for (i=0; i<L; i++) printf(" %.3f ", samp->x[i]); printf("\n"); printf("# pdf ="); for (i=0; i<L; i++) printf(" %.3f ", samp->pdf[i]); printf("\n"); printf("# cdf ="); for (i=0; i<L; i++) printf(" %.3f ", samp->cdf[i]); printf("\n"); printf("# totPdf = %g\n", samp->totPdf); printf("# x_mean = %g\n", samp->x_mean); return; } void set_sampler_t(sampler_t *samp, int setTotalToOne) { //-- Let p(x) = input pdf, q(x) = normalized pdf. //-- If setTotalToOne = 0, the input pdf is considered to contain physical information: //-- totPdf = integration over p(x) //-- x_mean = integration over x*p(x) //-- If setTotalToOne = 1, the input pdf is considered to be normalized, so: //-- totPdf = integration over q(x) = 1.0 //-- x_mean = integration over x*q(x) //-- In both cases, samp->pdf always represents q(x). double *x = samp->x; double *pdf = samp->pdf; double *cdf = samp->cdf; int length = samp->length; double totPdf = 0; double x_mean = 0; int i; //-- Compute total pdf and <x> totPdf += 0.5 * (pdf[0] + pdf[length-1]); x_mean += 0.5 * (pdf[0] * x[0] + pdf[length-1] * x[length-1]); for (i=1; i<=length-2; i++) { totPdf += pdf[i]; x_mean += pdf[i] * x[i]; } //-- Normalization for (i=0; i<length; i++) pdf[i] /= totPdf; samp->totPdf = totPdf * samp->dx; //-- Normalization by bin width samp->x_mean = x_mean * samp->dx; //-- Normalization by bin width if (setTotalToOne) { samp->totPdf = 1.0; samp->x_mean /= samp->totPdf; } //-- Fill cdf cdf[0] = 0; for (i=1; i<length; i++) cdf[i] = cdf[i-1] + 0.5 * (pdf[i-1] + pdf[i]); return; } double execute_sampler_t(sampler_t *samp, double x) { int length = samp->length; double *cdf = samp->cdf; double *value = samp->x; int i; for (i=1; i<length; i++) { if (cdf[i] >= x) break; } double r = (x - cdf[i-1]) / (cdf[i] - cdf[i-1]); return (1-r)*value[i-1] + r*value[i]; } //---------------------------------------------------------------------- //-- Functions related to sampler_arr sampler_arr *initialize_sampler_arr(int length, int nbPoints) { sampler_arr *sampArr = (sampler_arr*)malloc(sizeof(sampler_arr)); sampArr->length = length; sampArr->array = (sampler_t**)malloc(length * sizeof(sampler_t*)); int i; for (i=0; i<length; i++) sampArr->array[i] = initialize_sampler_t(nbPoints); return sampArr; } void free_sampler_arr(sampler_arr *sampArr) { int i; if (sampArr->array) { for (i=0; i<sampArr->length; i++) {free_sampler_t(sampArr->array[i]); sampArr->array[i] = NULL;} } free(sampArr); sampArr = NULL; return; } //---------------------------------------------------------------------- //-- Functions related to FFT_t FFT_t *initialize_FFT_t(int N1, int N2) { FFT_t *transformer = (FFT_t*)malloc(sizeof(FFT_t)); transformer->N1 = N1; transformer->N2 = N2; transformer->length = N1 * N2; transformer->length_f = N1 * (N2/2 + 1); //-- Allocate direct space elements transformer->before = (double*)calloc(transformer->length, sizeof(double)); transformer->kernel = (double*)calloc(transformer->length, sizeof(double)); transformer->after = (double*)calloc(2 * transformer->length_f, sizeof(double)); //-- Allocate Fourier space elements transformer->before_f = (fftw_complex*)fftw_malloc(transformer->length_f * sizeof(fftw_complex)); transformer->kernel_f = (fftw_complex*)fftw_malloc(transformer->length_f * sizeof(fftw_complex)); transformer->after_f = (fftw_complex*)fftw_malloc(transformer->length_f * sizeof(fftw_complex)); //-- Allocate fftw_plan elements transformer->before_p = fftw_plan_dft_r2c_2d(N1, N2, transformer->before, transformer->before_f, FFTW_ESTIMATE); transformer->kernel_p = fftw_plan_dft_r2c_2d(N1, N2, transformer->kernel, transformer->kernel_f, FFTW_ESTIMATE); transformer->after_p = fftw_plan_dft_c2r_2d(N1, N2, transformer->after_f, transformer->after, FFTW_ESTIMATE); return transformer; } void free_FFT_t(FFT_t *transformer) { if (transformer->before) {free(transformer->before); transformer->before = NULL;} if (transformer->kernel) {free(transformer->kernel); transformer->kernel = NULL;} if (transformer->after) {free(transformer->after); transformer->after = NULL;} if (transformer->before_f) {fftw_free(transformer->before_f); transformer->before_f = NULL;} if (transformer->kernel_f) {fftw_free(transformer->kernel_f); transformer->kernel_f = NULL;} if (transformer->after_f) {fftw_free(transformer->after_f); transformer->after_f = NULL;} if (transformer->before_p) {fftw_destroy_plan(transformer->before_p); transformer->before_p = NULL;} if (transformer->kernel_p) {fftw_destroy_plan(transformer->kernel_p); transformer->kernel_p = NULL;} if (transformer->after_p) {fftw_destroy_plan(transformer->after_p); transformer->after_p = NULL;} free(transformer); transformer = NULL; return; } void reset_FFT_t(FFT_t *transformer) { int i; for (i=0; i<transformer->length; i++) transformer->before[i] = 0.0; return; } void execute_FFT_t(FFT_t *transformer) { fftw_execute(transformer->before_p); //-- Complex coefficient multiplication in Fourier space int i; for (i=0; i<transformer->length_f; i++) { transformer->after_f[i][0] = transformer->before_f[i][0] * transformer->kernel_f[i][0] - transformer->before_f[i][1] * transformer->kernel_f[i][1]; transformer->after_f[i][1] = transformer->before_f[i][0] * transformer->kernel_f[i][1] + transformer->before_f[i][1] * transformer->kernel_f[i][0]; } fftw_execute(transformer->after_p); //-- Rescale for (i=0; i<transformer->length; i++) transformer->after[i] /= (double)transformer->length; return; } //---------------------------------------------------------------------- //-- Functions related to hist_t hist_t *initialize_hist_t(int length) { //-- length = number of bins //-- dx = bin width //-- n_tot = total counts //-- *x_lower = lower limit of each bin //-- x_max; = maximal limit //-- *n = histogram hist_t *hist = (hist_t*)malloc(sizeof(hist_t)); hist->length = length; hist->dx = 0.0; hist->x_lower = (double*)calloc(length, sizeof(double)); hist->x_max = 0.0; hist->n = (int*)calloc(length, sizeof(int)); hist->n_tot = 0; return hist; } void free_hist_t(hist_t *hist) { if (hist->x_lower) {free(hist->x_lower); hist->x_lower = NULL;} if (hist->n) {free(hist->n); hist->n = NULL;} free(hist); hist = NULL; return; } void print_hist_t(hist_t *hist) { printf("# hist_t\n"); printf("# Number of bins = %d\n", hist->length); printf("# Bin width = %g\n", hist->dx); printf("# Total counts = %d\n", hist->n_tot); printf("#\n"); printf("# bin n\n"); int i; for (i=0; i<hist->length; i++) printf(" [%9g, %9g] %6d\n", hist->x_lower[i], hist->x_lower[i]+hist->dx, hist->n[i]); return; } void set_hist_t(hist_t *hist, double x_min, double x_max) { int length = hist->length; double dx = (x_max - x_min) / (double)length; hist->dx = dx; hist->n_tot = 0; int i; for (i=0; i<length; i++) { hist->x_lower[i] = x_min + i * dx; hist->n[i] = 0; } hist->x_max = hist->x_lower[length-1] + dx; return; } void reset_hist_t(hist_t *hist) { int i; for (i=0; i<hist->length; i++) hist->n[i] = 0; return; } void push_hist_t(hist_t *hist, double x) { double *x_lower = hist->x_lower; if (x < x_lower[0] || x >= hist->x_max) { printf("Value out of range, not pushed into histogram\n"); return; } int i; for (i=0; i<hist->length-1; i++) { if (x_lower[i+1] > x) break; } hist->n[i] += 1; hist->n_tot += 1; return; } void silentPush_hist_t(hist_t *hist, double x) { double *x_lower = hist->x_lower; if (x < x_lower[0]) return; if (x >= hist->x_max) return; int i; for (i=0; i<hist->length-1; i++) { if (x_lower[i+1] > x) break; } hist->n[i] += 1; hist->n_tot += 1; return; } hist_t *deepCopy_hist_t(hist_t *oldHist) { hist_t *newHist = initialize_hist_t(oldHist->length); newHist->dx = oldHist->dx; newHist->n_tot = oldHist->n_tot; newHist->x_max = oldHist->x_max; int i; for (i=0; i<oldHist->length; i++) { newHist->x_lower[i] = oldHist->x_lower[i]; newHist->n[i] = oldHist->n[i]; } return newHist; } //---------------------------------------------------------------------- //-- Functions related to RNG u_int64_t renewSeed() { FILE *file = fopen("/dev/urandom","r"); u_int64_t seed; if (file == NULL) seed = 0; else { int state = fread(&seed, sizeof(u_int64_t), 1, file); fclose(file); } return seed; } gsl_rng *initializeGenerator() { u_int64_t seed = renewSeed(); gsl_rng *generator = gsl_rng_alloc(gsl_rng_default); gsl_rng_set(generator, seed); return generator; } //-- Use the following functions: //-- double gsl_ran_flat(const gsl_rng *r, double a, double b) //-- double gsl_ran_gaussian(const gsl_rng *r, double sigma) //---------------------------------------------------------------------- //-- Functions related to stopwatch //-- Use the following functions: //-- clock_t start = clock(); //-- clock_t finish = clock(); //-- double duration = (double)(finish - start) / CLOCKS_PER_SEC; void printTime(clock_t start, clock_t stop) { double duration = (double)(stop - start) / CLOCKS_PER_SEC; int hours = (int)(duration / 3600); double remain = fmod(duration, 3600); int minutes = (int)(remain / 60); double seconds = fmod(remain, 60); if (hours == 0) { if (minutes == 0) printf("Computation time = %.2f secs\n", duration); else printf("Computation time = %d m %d s\n", minutes, (int)seconds); } else printf("Computation time = %d h %d m %d s\n", hours, minutes, (int)seconds); return; } void routineTime(clock_t start, clock_t stop) { double duration = (double)(stop - start) / CLOCKS_PER_SEC; int hours = (int)(duration / 3600); double remain = fmod(duration, 3600); int minutes = (int)(remain / 60); double seconds = fmod(remain, 60); if (hours == 0) { if (minutes == 0) printf("routine time = %.2f secs\n", duration); else printf("routine time = %d m %d s\n", minutes, (int)seconds); } else printf("routine time = %d h %d m %d s\n", hours, minutes, (int)seconds); return; } //---------------------------------------------------------------------- //-- Math functions int imod(int N, int i) { //-- mod function ranged in [0, N-1] if (i < 0) return imod(N, i + N); if (i >= N) return imod(N, i - N); return i; } int imodc(int N, int i) { //-- mod function centered on 0, positive side is priviledged if N is even if (i <= -N + N/2) return imodc(N, i + N); if (i > N/2) return imodc(N, i - N); return i; } //----------------------------------------------------------------------
C
/* * console.h * * Created on: 27.01.2015 * Author: pascal */ #ifndef CONSOLE_H_ #define CONSOLE_H_ #include "stddef.h" #include "stdint.h" #include "stdbool.h" #include "lock.h" #define CONSOLE_AUTOREFRESH 1 #define CONSOLE_AUTOSCROLL 2 typedef struct{ uint8_t x, y; }cursor_t; typedef struct{ uint8_t id; char *name; uint8_t flags; void* waitingThread; lock_t lock; void *buffer; uint16_t height, width; uint8_t color; cursor_t cursor; char ansi_buf[16]; uint8_t ansi_buf_ofs; cursor_t saved_cursor; char *inputBuffer; size_t inputBufferSize, inputBufferStart, inputBufferEnd; }console_t; extern console_t initConsole; extern console_t *activeConsole; void console_Init(); console_t *console_create(char *name, uint8_t color); console_t *console_getByName(char *name); void console_ansi_write(console_t *console, char c); void console_write(console_t *console, char c); void console_clear(console_t *console); void console_clearLine(console_t *console, uint16_t line); void console_switch(uint8_t page); void console_changeColor(console_t *console, uint8_t color); void console_setCursor(console_t *console, cursor_t cursor); #endif /* CONSOLE_H_ */
C
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { srand(time(0)); int max = 0; int max_num = 0; for (int i = 1000; i < 1003; i++) { int ran = rand() % 101; printf("%d : %d", i, ran); printf("\n"); if (max < ran) { max = ran; max_num = i; } } printf("1 : %d : %d", max_num, max); printf("\n"); return 0; }
C
#include "gpio_cfg.h" void Pin_Cfg(GPIO_TypeDef * GPIO, uint8_t pin, GPIO_MODER_Type mode, GPIO_OTYPER_Type type, GPIO_OSPEEDR_Type speed, GPIO_PUPDR_Type pull, GPIO_AF_Type af) { GPIO->MODER = (GPIO->MODER & ((uint32_t)~(0x03 << (pin * 2)))) | (mode << (pin * 2)); GPIO->OTYPER = (GPIO->OTYPER & ((uint32_t)~(0x01 << pin))) | (type << pin); GPIO->OSPEEDR = (GPIO->OSPEEDR & ((uint32_t)~(0x03 << (pin * 2)))) | (speed << (pin * 2)); GPIO->PUPDR = (GPIO->PUPDR & ((uint32_t)~(0x03 << (pin * 2)))) | (pull << (pin * 2)); if (af != AF_NONE) { if (pin > 7) { GPIO->AFR[1] = (GPIO->AFR[1] & ((uint32_t)~(0x0F << ((pin - 8) * 4)))) | (af << ((pin - 8) * 4)); } else { GPIO->AFR[0] = (GPIO->AFR[0] & ((uint32_t)~(0x0F << (pin * 4)))) | (af << ((pin) * 4)); } } }
C
#include "windows.h" #include "stdio.h" int main(){ char mensaje[20]; DWORD leidos; HANDLE hStdln=GetStdHandle(STD_INPUT_HANDLE); SECURITY_ATTRIBUTES pipeSeg={sizeof(SECURITY_ATTRIBUTES), NULL, TRUE}; ReadFile(hStdln, mensaje, sizeof(mensaje), &leidos, NULL); printf("Mensaje recibido del proceso padre: %s\n", mensaje); CloseHandle(hStdln); printf("Termina el proceso hijo, continua el proceso padre.\n"); return 0; }
C
#ifndef S2PP_MSG_H__ #define S2PP_MSG_H__ #include <stdint-gcc.h> static void send_msg(const uint32_t addr, const uint32_t data) { static const uint32_t offset = 0; asm volatile("ecowx %0, %1, %2" : /* output */ : "r"(data), "r"(addr), "r"(offset)/* input */ : /* clobber */); } static uint32_t recv_msg(const uint32_t addr) { uint32_t rv; static const uint32_t offset = 0; asm volatile("eciwx %0, %1, %2" : "=r"(rv) /* output */ : "r"(addr), "r"(offset) /* input */ : /* clobber */); return rv; } /** Query the empty flag of the message queue to determine if messages can be * received. */ static uint32_t msg_waiting(uint32_t addr) { uint32_t rv; static const uint32_t offset = 4; asm volatile("eciwx %0, %1, %2" : "=r"(rv) /* output */ : "r"(addr), "r"(offset) /* input */ : /* clobber */); return (rv == 1) ? 0 : 1; } #endif
C
/* exall.c */ #include "ram_includes.h" #include "ram.h" #include "dos/exall.h" /* also works for examinefh, since fh_Arg1 == lock for me (object = 0) */ LONG exnext (pkt,object) struct DosPacket *pkt; LONG object; /* 0 = examine object, 1 = exnext */ /* 2 = examine all */ { struct FileInfoBlock *ivec; struct node *node; struct node *ptr; struct lock *lock; lock = (struct lock *) (pkt->dp_Arg1 << 2); ptr = checklock(lock); if (ptr == NULL) return FALSE; if (object == 2) /* ExAll */ return exall(ptr,pkt); ivec = (struct FileInfoBlock *) (pkt->dp_Arg2 << 2); node = (struct node *) ivec->fib_DiskKey; /* check for whether the file exists */ if (object != 0 && node != ptr) { /* see if the thing pointed to by the lock has been modified */ if (lock->delcount != ptr->delcount) { /* the directory has been modified. rescan. */ struct node *n; for (n = ptr->list; n; n = n->next) { if (n == node) break; } if (!n) { /* object was deleted. restart scan */ /* it would be nice to pick up, but this is */ /* at least safe. */ node = ptr; } /* else it's still in the directory */ } /* else the directory hasn't been modified */ } /* so we can catch files being deleted from under us */ lock->delcount = ptr->delcount; return setinfo(ivec,object == 0 ? ptr : ptr == node ? node->list : node->next); } LONG exall (struct node *node, struct DosPacket *dp) { struct ExAllData *ed = (void *) dp->dp_Arg2; struct ExAllData *lasted = NULL; LONG size = dp->dp_Arg3; LONG data = dp->dp_Arg4; struct ExAllControl *ec = (void *) dp->dp_Arg5; struct node *curr; LONG savesize; /*kprintf("in exall for %s (0x%lx, %ld, %ld, 0x%lx)\n",node->name, dp->dp_Arg2,dp->dp_Arg3,dp->dp_Arg4,dp->dp_Arg5); */ if (node->type != ST_USERDIR) { fileerr = ERROR_OBJECT_WRONG_TYPE; return FALSE; } /* check the data value */ if (data < ED_NAME || data > ED_COMMENT) { fileerr = ERROR_BAD_NUMBER; /* FIX!? */ return FALSE; } /* we leave pointer to next node in ec->eac_LastKey */ /* If it has been deleted, we're in deep shit. FIX! */ /* I COULD temporarily lock it, since ExAlls should */ /* always be finished. */ ec->eac_Entries = 0; /* no entries */ for (curr = ec->eac_LastKey ? (struct node *) ec->eac_LastKey : node->list; curr; curr = curr->next) { /*kprintf("Looking at %s\n",curr->name);*/ /* ok, we got here, fill in the buffer, check for overrun */ savesize = size; if (!fill_data(ed,data,curr,&size)) { /*kprintf("Out of space\n");*/ /* out of space, return partial */ if (lasted) lasted->ed_Next = NULL; /* last entry */ ec->eac_LastKey = (LONG) curr; return DOS_TRUE; } /* first do pattern matching */ if (ec->eac_MatchString) { /* use default match func */ if (!MatchPatternNoCase(ec->eac_MatchString, curr->name)) goto reject; } if (ec->eac_MatchFunc) { if (!do_match(ec,data,ed)) { reject: size = savesize; continue; } } /* remember the last entry so we can NULL out ed_Next */ lasted = ed; /*kprintf("adding entry (%ld)\n",ec->eac_Entries+1);*/ /* filled it in, bump count and move on */ ec->eac_Entries++; ed = ed->ed_Next; } /* make sure last ed_Next entry is NULL */ if (lasted) lasted->ed_Next = NULL; /*kprintf("Done\n");*/ /* finished, return that we're done (ERROR_NO_MORE_ENTRIES) */ fileerr = ERROR_NO_MORE_ENTRIES; return FALSE; } /* offsets for the first string for the different settings of data */ static UBYTE __far str_offset[ED_COMMENT] = { 8,12,16,20,32,36 }; LONG fill_data (struct ExAllData *ed, ULONG data, struct node *node, LONG *size) { UBYTE *p = ((UBYTE *) ed) + str_offset[data-1]; LONG mysize = 0; struct node *link = node; /* report most info from the thing hard-linked to */ /* name and type come from the link itself, all else from linked-to */ if (node->type == ST_LINKFILE || node->type == ST_LINKDIR) link = node->list; /* first take off required size */ /* initial ed MUST be on multiple of 2 boundary!!!! */ switch (data) { case ED_COMMENT: mysize += 4 + (link->comment ? strlen(link->comment) : 0) + 1; case ED_DATE: mysize += 3*4; case ED_PROTECTION: mysize += 4; case ED_SIZE: mysize += 4; case ED_TYPE: mysize += 4; case ED_NAME: mysize += 2*4 + strlen(node->name) + 1; if (mysize > *size) return FALSE; } if (mysize & 1) /* if would put next on odd boundary */ mysize++; *size -= mysize; /* we now know we have enough space - fill it in */ switch (data) { case ED_COMMENT: ed->ed_Comment = p; *p = '\0'; if (link->comment) strcpy(p,link->comment); p += strlen(p) + 1; /* point to space for name */ case ED_DATE: copydate(&(ed->ed_Days),&(link->date[0])); case ED_PROTECTION: ed->ed_Prot = link->prot; case ED_SIZE: ed->ed_Size = link->size; case ED_TYPE: ed->ed_Type = node->type; case ED_NAME: ed->ed_Name = p; strcpy(p,node->name); ed->ed_Next = (struct ExAllData *) (((LONG) ed) + mysize); } return TRUE; } /* this does the dirty work of examine, exnext */ LONG setinfo (ivec,ptr) struct FileInfoBlock *ivec; struct node *ptr; { LONG type; if (ptr == NULL) { fileerr = ERROR_NO_MORE_ENTRIES; return FALSE; } ivec->fib_DiskKey = (LONG) ptr; /* magic to user! */ type = ivec->fib_DirEntryType = ivec->fib_EntryType = ptr->type; /* out of order for speed */ CtoBcpy(ivec->fib_FileName,ptr->name); /* C strings to Bstr */ /* report most info from the thing hard-linked to */ if (type == ST_LINKFILE || type == ST_LINKDIR) ptr = ptr->list; ivec->fib_Protection = ptr->prot; ivec->fib_Size = ptr->size; ivec->fib_NumBlocks = (ptr->size >> BLKSHIFT) + 1; ivec->fib_Date.ds_Days = ptr->date[0]; ivec->fib_Date.ds_Minute = ptr->date[1]; ivec->fib_Date.ds_Tick = ptr->date[2]; ivec->fib_Comment[0] = '\0'; /* BSTR! */ /* handle null comments */ if (ptr->comment) CtoBcpy(ivec->fib_Comment,ptr->comment); /* C strings to bstr*/ return DOS_TRUE; }
C
//prepare: -lm #include <stdio.h> #include "number_theory.c" #include "integer_maths.c" /* The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million? */ bool is_circular_prime(unsigned number){ // assume given argument is prime unsigned length = digit_length(number, 10); unsigned coefficient = powi(10, length - 1); for (unsigned i = 1; i < length; i++){ unsigned digit = number % 10; number /= 10; number += digit * coefficient; if (!is_prime(number)){ return false; } } return true; } size_t circlular_primes_under(size_t limit){ if (limit < 2){ return 0; } barray* primes = sieve_of_erastosthenes(limit*10); size_t count = 1; // 2 is a circular prime for (size_t index = 3; index <= limit; index += 2){ // todo: if index is a circular prime then we can add it, and all of its cyclic permutations to the sum // then bset(primes, permutation, false) to skip over them later) // warning: may be repeats e.g. with 11 if (bget(primes, index) && is_circular_prime(index)){ count++; } } bfree(primes); return count; } int main(){ assert(digit_length(197, 10) == 3); assert(is_circular_prime(197)); assert(circlular_primes_under(100) == 13); printf("%lu\n", circlular_primes_under(1000000)); return 0; }
C
#include <stdio.h> #include <math.h> int main(int argc, const char *argv[]) { int a,b,c;double d,x1,x2; printf("请输入a、b、c的值\n"); scanf("%d%d%d",&a,&b,&c); getchar(); printf("%d%d%d\n",a,b,c); d = b*b-4*a*c; printf("%.2f\n",d); if(d>0){ x1 = (-b+sqrt(d))/2*a; x2 = (-b-sqrt(d))/2*a; printf("x1 = %.2f,x2 = %.2f\n",x1,x2); }else{ printf("输入错误,请重试!\n"); } // printf("x1 = %.2f,x2 = %.2f\n",x1,x2); return 0; }
C
#include<stdio.h> // main(), printf() // 1. #include : ( ϴ ɾ) // 2. <stdio.h> : (ٸ ִ ԽŲ.) void main() { printf("Hello world"); }
C
/* Given non-negative integer a and positive integer b as C-strings, return a pointer "array" char ** of length 2 containing the quotient and remainder of the result in that order. The quotient and remainder should both be pointer-strings and not character arrays; furthermore, their memory (and the memory of the entire pointer "array") should be dynamically allocated as the test cases will free the memory allocated for your result which would throw an error otherwise. Since the length of the pointer "array" is expected to be constant, there is no point in passing an int/size_t by reference and having your solution set it to the length of the output array. a and b can be very large (at the order of 10^150 to 10^200) As usual, your result should not have leading 0s require is disabled in JavaScript. Do it yourself ;-) */ #include <stdio.h> #include <stdlib.h> #include <string.h> void resize_char(char *a,int *sa){ if(a==NULL || *sa<1){ printf("\n Not possible in mylresize, debug print!"); printf("\nAlt value sa=%d",*sa); exit(1); } while(*sa>1 && a[(*sa)-1]=='0') (*sa)--; return; } int compare_char(char *a,int sa,char *b,int sb){ if(sa <= 0 || sb <= 0){ printf("\n Not possible in lcompare, debug print!"); printf("\nAlt value sa=%d sb=%d",sa,sb); exit(1); } if(sa==1 && sb==1) { if(a[0]==b[0]) return 0; else if(a[0]<b[0]) return -1; else return 1; } if(sa>sb) return 1; if(sa<sb) return -1; if(a[sa-1]<b[sb-1]) return -1; if(a[sa-1]>b[sb-1]) return 1; else return compare_char(a,sa-1,b,sb-1); } void inc_char(char *a, int sa, int index){ if(a==NULL || index<0 || index>=sa){ printf("\n Not possible in inc_char, debug print!"); printf("\nAlt value sa=%d index=%d",sa,index); exit(1); } a[index]+=1; if(a[index]>'9'){ a[index]='0'; inc_char(a,sa,index+1); } return; } void sub_char(char *a,int sa, char *b, int sb, int start){ //assuming a>=b if(sa < start+sb || start<0){ printf("\n Not possible in sub_char, debug print!"); printf("\nAlt value sa=%d sb=%d start=%d",sa,sb,start); exit(1); } if((start+sb == sa) && (a[sa-1]<b[sb-1])){ printf("\n Not possible in lsub, debug print!"); printf("\nAlt value sa=%d sb=%d start=%d",sa,sb,start); printf("a<b, only natural subtraction"); exit(1); } for(int i = start; i< sb + start; i++){ if(a[i]>=b[i-start]) a[i]-=b[i-start]-'0'; else{ a[i]= 10-(b[i-start]-a[i])+'0'; int j; for(j=1; a[i+j]==0;j++) a[i+j] = '9'; a[i+j]--; } } return; } void div_char(char *a,int *sa,char *b,int sb, char *q, int sq){ if(a==NULL || b ==NULL){ printf("\n Not possible in myldiv, debug print!"); printf("\nAlt value sa=%d sb=%d sq=%d",*sa,sb,sq); exit(1); } if(*sa<sb) return; if(((*sa)==sb) && (compare_char(a,*sa,b,sb)<0)) return; if(((*sa)==sb) && (compare_char(a,*sa,b,sb)==0)){ a[0]='0'; *sa=1; inc_char(q,sq,0); return; } if((*sa>=sb+1)){ while(*sa>=sb+1){ sub_char(a,*sa,b,sb,(*sa)-sb-1); inc_char(q,sq,(*sa)-sb-1); resize_char(a,sa); } div_char(a,sa,b,sb,q,sq); } else{ //here *sa==sb while(compare_char(a,*sa,b,sb)>=0){ sub_char(a,*sa,b,sb,0); inc_char(q,sq,0); resize_char(a,sa); } } return; } void reverse(char *x, int begin, int end){ char c; if (begin >= end) return; c = *(x+begin); *(x+begin) = *(x+end); *(x+end) = c; reverse(x, ++begin, --end); } char **divide_strings(char *a, char *b) { char **result = malloc(2 * sizeof(char *)); int d1s = (strlen(a) + 1); char * d1 = malloc(d1s * sizeof(char)); for(int i=0;i<d1s-1;i++) d1[i]=a[d1s-2-i]; d1[d1s-1]= '\0'; int d2s = (strlen(b) + 1); char * d2 = malloc(d2s * sizeof(char)); for(int i=0;i<d2s-1;i++) d2[i]=b[d2s-2-i]; d2[d2s-1]= '\0'; int dqs=(strlen(a) + 1); char *quotient = malloc(dqs * sizeof(char)); for(int i=0;i<dqs-1;i++) quotient[i]='0'; quotient[strlen(a)]= '\0'; char *remainder; d1s--;d2s--;dqs--; div_char(d1,&d1s,d2,d2s,quotient,dqs); resize_char(d1,&d1s); resize_char(quotient,&dqs); d1s++;dqs++; remainder = malloc(d1s * sizeof(char)); for(int i=0;i<d1s-1;i++) remainder[i]=d1[d1s-2-i]; remainder[d1s-1]= '\0'; char temp; quotient[dqs-1]= '\0'; reverse(quotient,0,dqs-2); *result = malloc((strlen(quotient) + 1) * sizeof(char)); *(result + 1) = malloc((strlen(remainder) + 1) * sizeof(char)); for (int i = 0; i < strlen(quotient); i++) *(*result + i) = quotient[i]; for (int i = 0; i < strlen(remainder); i++) *(*(result + 1) + i) = remainder[i]; *(*result + strlen(quotient)) = *(*(result + 1) + strlen(remainder)) = '\0'; free(d2); free(d1); free(quotient); free(remainder); return result; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* test.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddvorove <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/01/13 08:57:35 by ddvorove #+# #+# */ /* Updated: 2020/01/14 14:19:25 by ddvorove ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int ft_str_is_alpha(char *str); void ft_putchar(char c) { write(1, &c, 1); } int main(void) { char str[] ="salut, comment tu vas ? 42mots quarante-deux; cinquante+et+un"; printf("%s\n", str); printf("my func - %d\n\n", ft_str_is_alpha(str)); char str1[] = " 1zxcdsf!"; printf("%s\n", str1); printf("my func - %d\n\n", ft_str_is_alpha(str1)); char str2[] = "abcdefghiklmnop"; printf("%s\n", str2); printf("my func - %d\n\n", ft_str_is_alpha(str2)); char str3[] = ""; printf("%s\n", str3); printf("my func - %d\n\n", ft_str_is_alpha(str3)); return (0); }
C
#include"project.h" int decrypt4_file (char *file_name, char *key_file_name) { char *key_file_data, *enc_data, *dec_data; key_file_data = NULL; enc_data = NULL; dec_data = NULL; int i, j; key_file_data = reading_file (key_file_name); printf("Key file data: \n %s\n", key_file_data); enc_data = reading_file (file_name); printf("Encrypted file data: \n %s \n", enc_data); i = 0; j=0; unsigned char temp_ch; int n; while(1) { temp_ch = temp_ch ^ temp_ch; temp_ch = enc_data[i]; temp_ch = temp_ch >> 4; n = (int) temp_ch; if( n == 15) { break; } dec_data = realloc (dec_data, j+1); dec_data[j] = key_file_data[n]; j++; temp_ch = temp_ch ^ temp_ch; temp_ch = enc_data[i]; temp_ch = temp_ch << 4; temp_ch = temp_ch >> 4; n = (int) temp_ch; if( n == 15) { break; } dec_data = realloc (dec_data, j+1); dec_data[j] = key_file_data[n]; j++; i++; } dec_data[j] = '\0'; printf("Decrypted data:\n %s \n", dec_data); char *file_name_dec; file_name_dec = str_concatanate (file_name, "-decrypted"); FILE *fp_dec; fp_dec = fopen(file_name_dec, "w"); free(file_name_dec); fwrite(dec_data, j, 1 , fp_dec); free(dec_data); fclose(fp_dec); fflush(fp_dec); return 0; }
C
/* * Filename: teststrToULong.c * Author: Wenhui Tang * Userid: cs30xlv * Description: Unit test program to test the function strToULong. * Date: Oct. 30, 2013 */ #include "pa2.h" /* For strToLong() function prototype */ #include "test.h" /* For TEST() macro and stdio.h */ #include <errno.h> /* * unsigned long strToULong( char *str, int base ) * * Converts the passed in string into a long in the given base * prints error messages to stderr if number too large or if not an integer * */ void teststrToULong() { printf( "Testing strToULong()\n" ); TEST( strToULong( "17", 0 ) == 17 ); printf( "Finished running tests on strToULong()\n" ); } int main() { teststrToULong(); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* work_with_file.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: olaktion <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/25 14:07:26 by olaktion #+# #+# */ /* Updated: 2019/06/25 14:07:27 by olaktion ### ########.fr */ /* */ /* ************************************************************************** */ #include "player_stable.h" #include "../include/get_next_line.h" void read_file(t_system *sys) { char *line; int32_t fd; t_list *list; list = NULL; if ((fd = open(sys->map, O_RDONLY)) < 0) print_error("Error, bad file"); while (get_next_line(fd, &line)) { tmp_list(&list, (void *)line, ft_strlen(line)); ft_strdel(&line); } ft_strdel(&line); parse_all(sys, list); } void parse_all(t_system *sys, t_list *list) { parse_vertex(sys, list); parse_sec(sys, list); parse_player(sys, list); sys->sectors->ver_arr_len = 0; sys->sum_vert = 0; sys->sum_vert_pair = 0; free_tmp_list(&list); } void print_error(const char *msg) { ft_putendl(msg); exit(0); } void tmp_list(t_list **lst, const void *content, const size_t content_size) { t_list *tmp; if (!*lst) *lst = ft_lstnew(content, content_size); else { tmp = *lst; while (tmp->next) tmp = tmp->next; tmp->next = ft_lstnew(content, content_size); } } void free_tmp_list(t_list **head) { t_list *tmp; while (*head) { tmp = *head; ft_memdel(&tmp->content); ft_memdel((void *)&tmp); (*head) = (*head)->next; } ft_memdel((void **)head); }
C
#include<stdio.h> int main() { int n,m; scanf("%d",&n); for(;n%10!=1;) { n=n/10; if (n == 0) break; } if (n==0) printf("No\n"); else printf("Yes\n"); return 0; }
C
#ifndef UTIL #define UTIL #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #include <stdbool.h> void create_array(int array_size, int **array); void create_array_x(int array_size, int **array, int x); void spaces(int amount); void print_array(int size, int *array); void print_complexity(int n, double time, double (*function_pointer)(int)); inline bool greater(int a, int b) { return a > b; } inline bool greater_equal(int a, int b) { return a >= b; } inline bool smaller(int a, int b) { return a < b; } inline bool smaller_equal(int a, int b) { return a <= b; } bool is_sorted(int size, int *array, bool (*compare_function)(int, int)); inline void swap(int *a, int *b) { int c = *a; *a = *b; *b = c; } // if a<=x<=b inline bool in_range(int x, int a, int b) { return x >= a && x <= b; } #define ASCII_DIGITS 48, 57 #define ASCII_UPPERCASE 65, 90 #define ASCII_LOWERCASE 97, 122 #endif
C
/*Tarea 3 -Peralta Luna Karen Lisseth -S17002346 */ #include <stdio.h> #include <stdlib.h> typedef struct nodo_padre { int dato; struct punteros_hijos *frente; struct punteros_hijos *final; }n_padre; typedef struct punteros_hijos { n_padre * raiz; struct punteros_hijos *hermano; }hijo; /*--------------------------------------*/ hijo *crear_cola(n_padre *nhijo); n_padre *crear_nodo_p(int d); int insertar_nuevo_nodo(n_padre **raiz,int d,int p); void imprimir_hojas(hijo *frente); void imprimir_arbol(n_padre *raiz); hijo *buscar_entre_hermanos(hijo *hermanos,int padre); int insertar_nuevo_hermano(hijo *nhijo,hijo **fin); int main(int argc, char const *argv[]) { n_padre *raiz=NULL; //raiz=crear_nodo_p(65); insertar_nuevo_nodo(&raiz,65,0);//A insertar_nuevo_nodo(&raiz,66,65);//B insertar_nuevo_nodo(&raiz,67,65);//C insertar_nuevo_nodo(&raiz,68,66);//D insertar_nuevo_nodo(&raiz,69,66);//E insertar_nuevo_nodo(&raiz,70,66);//F insertar_nuevo_nodo(&raiz,71,67);//G insertar_nuevo_nodo(&raiz,72,67);//H insertar_nuevo_nodo(&raiz,73,68);//I insertar_nuevo_nodo(&raiz,74,70);//J insertar_nuevo_nodo(&raiz,75,70);//K insertar_nuevo_nodo(&raiz,76,72);//L imprimir_arbol(raiz); return 0; } hijo *crear_cola(n_padre *nhijo) { hijo *neweh=(hijo*) malloc(sizeof(hijo)); if(!neweh) return NULL; neweh->raiz=nhijo; neweh->hermano=NULL; return neweh; } n_padre *crear_nodo_p(int d) { n_padre *newe=(n_padre*)malloc(sizeof(n_padre)); if(!newe) return NULL; newe->dato=d; newe->frente=NULL; newe->final=NULL; return newe; } int insertar_nuevo_hermano(hijo *nhijo,hijo **fin) { (*fin)->hermano=nhijo; (*fin)=nhijo; return 1; } hijo *buscar_entre_hermanos(hijo *hermanos,int padre) { if(!hermanos) return NULL; if(hermanos->raiz->dato==padre) return hermanos; buscar_entre_hermanos(hermanos->hermano,padre); } int insertar_nuevo_nodo(n_padre **raiz,int d,int p) { if(!(*raiz)){ (*raiz)=crear_nodo_p(d); return 1; } if((*raiz)->dato==p) { n_padre *aux_n=crear_nodo_p(d); if(!(*raiz)->frente) { (*raiz)->frente=crear_cola(aux_n); (*raiz)->final=(*raiz)->frente; return 1; } hijo *aux_h=crear_cola(aux_n); insertar_nuevo_hermano(aux_h,&(*raiz)->final); return 1; } hijo *aux=(*raiz)->frente; if(aux){ hijo *pb=buscar_entre_hermanos(aux,p); if(pb){ insertar_nuevo_nodo(&pb->raiz,d,p); return 1; } if(aux->hermano) insertar_nuevo_nodo(&aux->hermano->raiz,d,p); insertar_nuevo_nodo(&aux->raiz,d,p); } return 0; } void imprimir_hojas(hijo *frente) { if(frente) { imprimir_arbol(frente->raiz); //printf("hijo: %c\n",frente->raiz->dato); imprimir_hojas(frente->hermano); } return; } void imprimir_arbol(n_padre *raiz) { if(raiz) { printf("Padre:%c\n",raiz->dato); imprimir_hojas(raiz->frente); } return; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_str_charnoutrev.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: aroulin <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/01/01 00:00:21 by aroulin #+# #+# */ /* Updated: 2016/01/01 00:00:42 by aroulin ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include <unistd.h> #include "libft.h" static int ft_charinstr(char c, char *str) { int boolean; boolean = 0; while (*str) { if (c == *str) { boolean = 1; break ; } str++; } return (boolean); } char *ft_str_charnoutrev(char const *s, char *listc, size_t start) { size_t total; size_t len; size_t i; char *freshstr; len = 0; i = 0; total = 0; while (s[i]) if (!ft_charinstr(s[i++], listc) || i < start) total++; freshstr = (char *)malloc(total + 1); i = 0; len = 0; if (freshstr != NULL) { while (s[total - i]) { if (!ft_charinstr(s[i], listc) || i < start) freshstr[len++] = s[i]; i++; } freshstr[len] = '\0'; } return (freshstr); }
C
#include<stdio.h> #include<string.h> int main(){ int T,N,i,j,G,W; int prices[1005],weight[1005]; int table[1005][35]; int total,t; scanf("%d",&T); while(T--){ scanf("%d",&N); for(i=1;i<=N;i++) scanf("%d%d",&prices[i],&weight[i]); memset(table,0,sizeof(table)); for(i=1;i<=N;i++) for(j=0;j<=30;j++) if(j<weight[i]) table[i][j]=table[i-1][j]; else if(table[i-1][j]<(t=table[i-1][j-weight[i]]+prices[i])) table[i][j]=t; else table[i][j]=table[i-1][j]; scanf("%d",&G); total=0; while(G--){ scanf("%d",&W); total+=table[N][W]; } printf("%d\n",total); } return 0; }
C
/** * @file p1ch.c * @author Jayanth * @brief Inputs given by player1 and storing them in grid * @version 0.1 * @date 2021-04-16 * * @copyright Copyright (c) 2021 * */ #include"function.h" /** * @brief Inputs given by player1 and storing them in grid * * @param k * @param g * @param z */ void p1ch(int k,char** g,int z) { if(k==1) g[0][0]='X'; else if(k==2) g[0][1]='X'; else if(k==3) g[0][2]='X'; else if(k==4) g[1][0]='X'; else if(k==5) g[1][1]='X'; else if(k==6) g[1][2]='X'; else if(k==7) g[2][0]='X'; else if(k==8) g[2][1]='X'; else if(k==9) g[2][2]='X'; }
C
#include <stdio.h> #include<windows.h> #include<string.h> void reverse(char *str) { int len = strlen(str);//ַ char *left = str; char *right = str + len - 1; char tmp = 0; while (left<right)//ҽַ { tmp = *left; *left = *right; *right = tmp; left++; right--; } } int main() { char arr[] = "Hello World!"; reverse(arr); printf("%s\n", arr); system("pause"); return 0; }