language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include "head.h" int main () { read(); // read from file char ribbon[256]; scanf("%255[^\n]s", &ribbon); // input pita // CHECK THE RIBBON STARTKATA(ribbon); // start char penumpang1[32]; // untuk kata pertama strcpy(penumpang1, GETCKATA()); INCKATA(ribbon); // cek kata selanjut nya // kalau kata kedua nya memenuhi pola 1 2 3 maka panggil prosedur if (strcmp(GETCKATA(), "turun") == 0) { turun(penumpang1); } else if (strcmp(GETCKATA(), "duduk") == 0) { duduk(ribbon, penumpang1); } else if (strcmp(GETCKATA(), "dan") == 0) { sebelahan(ribbon, penumpang1); } else { // kalau salah printf("Input yang dimasukkan salah. . .\n"); } // WRITE TO FILE write(); // cek txt // int i; // for (i = 0; i < n; i++) { // printf("%s %s\n", record[i].kiri, record[i].kanan); // } return 0; } /* Asumsinya bus damri tersebut mempunyai 2 banjar kursi ke samping dan 20 baris ke belakang. Format kalimat masukan dibatasi : 1. [namapenumpang] turun. 2. [namapenumpang1] duduk di sebelah kiri/kanan/depan/belakang [namapenumpang2]. 3. [namapenumpang1] dan [namapenumpang2] duduk bersebelahan. Tidak ada kemungkinan supir damri menginput kalimat selain dari ketiga itu. Bonus : Validasi jika input nama di barisan kursi yang sudah penuh, misalnya Dina duduk di sebelah kanan Teti, maka ada warning seperti ini : Barisan kursi sudah penuh. Silahkan input ulang : [masukan baru dengan format kalimat 1, 2 atau 3] Contoh Masukan Dudu duduk di sebelah kanan Dida. Contoh Keluaran Pada file tkursi.txt akan terekam : Dida Dudu dummy dummy Contoh Masukan 2 Dida turun. Contoh Keluaran 2 Rekaman tkursi.txt : Kosong Dudu dummy dummy Contoh Masukan 3 Tata dan Teti duduk bersebelahan. Contoh Keluaran 3 Rekaman tkursi.txt : Kosong Dudu Tata Teti dummy dummy */
C
/* fakeLinkage - Fake some linkage data. */ #include "common.h" #include "linefile.h" #include "hash.h" #include "options.h" #include "jksql.h" #include "hdb.h" static char const rcsid[] = "$Id: fakeLinkage.c,v 1.1 2006/09/13 03:01:48 kent Exp $"; void usage() /* Explain usage and exit. */ { errAbort( "fakeLinkage - Fake some linkage data\n" "usage:\n" " fakeLinkage database output\n" "options:\n" " -xxx=XXX\n" ); } static struct optionSpec options[] = { {NULL, 0}, }; void fakeChromLinkage(char *database, char *chrom, FILE *f) /* Generate fake linkage data for one chromosome */ { int size = hdbChromSize(database, chrom); int stepSize = 5000000; int pos; uglyf("faking %s %d\n", chrom, size); struct sqlConnection *conn = hAllocConn(); for (pos=0; pos<size; pos += stepSize) { int rowOffset = 0; char query[512]; safef(query, sizeof(query), "select name from stsMap where chrom='%s' and chromStart >= %d && chromStart < %d", chrom, pos, pos+stepSize); struct sqlResult *sr = sqlGetResult(conn, query); char **row = sqlNextRow(sr); if (row != NULL) { double x; if (rand()%250 == 0) { x = 3.5 + (double)rand()/RAND_MAX; } else { x = (double)rand() / RAND_MAX + 0.001; x = log(x) + 1; if (x < -1) x = -1; } fprintf(f, "%s\t%f\n", row[0], x); } sqlFreeResult(&sr); } hFreeConn(&conn); } void fakeLinkage(char *database, char *output) /* fakeLinkage - Fake some linkage data. */ { FILE *f = mustOpen(output, "w"); hSetDb(database); int i; for (i=1; i<=22; ++i) { char chromName[256]; safef(chromName, sizeof(chromName), "chr%d", i); fakeChromLinkage(database, chromName, f); } carefulClose(&f); } int main(int argc, char *argv[]) /* Process command line. */ { optionInit(&argc, argv, options); if (argc != 3) usage(); fakeLinkage(argv[1], argv[2]); return 0; }
C
#include "c_stack.h" #include "c_deque.h" c_stack* c_stack_create(dump_func dump, release_func release, size_t elem_size) { return c_deque_create(dump, release, elem_size); } c_stack* c_stack_clone(const c_stack *src) { return c_deque_clone(src); } void c_stack_destroy(c_stack *s) { c_deque_destroy(s); } void* c_stack_push(c_stack *s, const void *elem) { return c_deque_add_last(s, elem); } void c_stack_pop(c_stack *s) { c_deque_remove_last(s); } void* c_stack_top(const c_stack *s) { return c_deque_get_last(s); } void c_stack_clear(c_stack *s) { c_deque_clear(s); } int c_stack_is_empty(const c_stack *s) { return c_deque_is_empty(s); } int c_stack_size(const c_stack *s) { return c_deque_size(s); }
C
// Demonstration of a technique for inheritance in C. Internally, // this is sort of how languages like C++ and Java provide inheritance // and function overriding. // There are more sophisticated ways to do this, better for larger // projects, but this is not a bad approach for a first look at object // orientation in C. #include <stdio.h> #include <stdlib.h> #include <stdbool.h> /************************************************************************ * Base class, Cell, just holds a field for the width of the cell. ************************************************************************/ typedef struct { // Width of the cell. int width; } Cell; // Like a constructor for a Cell. Dynamically allocate it, fill in // its field and return a pointer to a new Cell object. Cell *makeCell( int width ) { // Allocate a Cell and fill in its fields (just one) Cell *this = (Cell *)malloc( sizeof( Cell ) ); this->width = width; return this; } /************************************************************************ * Derived class (subclass), Money keeps all the same fields as Cell * (in the same layout). It adds a field for storign a monetary value * in the memory after the fields inherited from the base class. ************************************************************************/ typedef struct { // Field "inherited" from Cell int width; // A new field for storing a monetory value. int val; } Money; // Like a constructor for Money. Create, initialize and return a pointer // to a new Money object. Money *makeMoney( int width, int val ) { // Allocate a Money object and fill in its fields Money *this = (Money *)malloc( sizeof( Money ) ); this->width = width; this->val = val; return this; } /**********************************************************************/ // A utilitiy fuction to print a horizontal separator between rows of the // spreadsheet. void printSeparator( Cell *row[], int len ) { for ( int i = 0; i < 3; i++ ) { printf( "+" ); // As in main, we're getting the width field out of each cell. int width = row[ i ]->width; for ( int j = 0; j < width; j++ ) printf( "-" ); } printf( "+\n" ); } int main() { // A grid of cells in our spreadsheet. Cell *sheet[ 2 ][ 3 ]; // Fill in cells of the spreadsheet. Notice, we have to cast here // for anything that's not a real Cell pointer. The programming // language doesn't really know about the object orientation tricks // we're doing. ... It would sure be nice if we had a language that // did. ... sheet[ 0 ][ 0 ] = makeCell( 10 ); sheet[ 0 ][ 1 ] = (Cell *) makeMoney( 12, 375 ); sheet[ 0 ][ 2 ] = makeCell( 16 ); sheet[ 1 ][ 0 ] = makeCell( 10 ); sheet[ 1 ][ 1 ] = (Cell *) makeMoney( 12, 890 ); sheet[ 1 ][ 2 ] = makeCell( 16 ); // Print out an outline for the cells. for ( int i = 0; i < 2; i++ ) { printSeparator( sheet[ i ], 3 ); for ( int j = 0; j < 3; j++ ) { // Here, we're just printing space for the conents of each cell. // Every cell has a width field, (at the same offset from the // start of the struct), so we can access it using the same // code, even though some of these point to Cell instances and // some point to Money. Cell *c = sheet[ i ][ j ]; printf( "|%*s", c->width, "" ); } printf( "|\n" ); } printSeparator( sheet[ 1 ], 3 ); // These objects are all dynamically allocated. We should free // their memory. Good thing free doesn't require us to say how much // memory we're freeing, since these objects are really of different // sizes. for ( int i = 0; i < 2; i++ ) { for ( int j = 0; j < 3; j++ ) { free( sheet[ i ][ j ] ); } } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ball.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gsauvair <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/05/03 23:33:28 by gsauvair #+# #+# */ /* Updated: 2015/05/03 23:33:29 by gsauvair ### ########.fr */ /* */ /* ************************************************************************** */ #include "arkanoid.h" static void move_ball(t_env *env) { env->ball.x += env->ball.move_x; env->ball.y += env->ball.move_y; if ((env->ball.x + env->ball.move_x) >= 0.99 || (env->ball.x + env->ball.move_x) <= -0.99) env->ball.move_x *= -1; if ((env->ball.y + env->ball.move_y) >= 0.99) env->ball.move_y *= -1; if ((env->ball.y + env->ball.move_y) <= -0.99) { env->life -= 1; env->ball.x = 0.f; env->ball.y = -0.4f; env->ball.move_x = 0.008f; env->ball.move_y = -0.008f; the_ball(env); } } void the_ball(t_env *env) { move_ball(env); glBegin(GL_QUADS); glColor3f(0.9f, 0.9f, 0.9f); glVertex2f(-0.015f + env->ball.x, -0.02f + env->ball.y); glVertex2f(0.015f + env->ball.x, -0.02f + env->ball.y); glVertex2f(0.015f + env->ball.x, 0.02f + env->ball.y); glVertex2f(-0.015f + env->ball.x, 0.02f + env->ball.y); glEnd(); }
C
/* Public domain */ /* * C-string related routines. */ #ifdef AG_UNICODE /* * Return the length of a UCS-4 string in characters (not including NUL). */ #ifdef AG_INLINE_HEADER static __inline__ AG_Size _Pure_Attribute AG_LengthUCS4(const AG_Char *_Nonnull ucs) #else AG_Size ag_length_ucs4(const AG_Char *ucs) #endif { AG_Size len; for (len = 0; *ucs != '\0'; ucs++) { len++; } return (len); } /* * Compute # bytes that would be needed to encode an UCS-4 char in UTF-8. */ #ifdef AG_INLINE_HEADER static __inline__ int _Const_Attribute AG_CharLengthUTF8FromUCS4(AG_Char ch) #else int ag_char_length_utf8_from_ucs4(AG_Char ch) #endif { if (ch < 0x80) { return (1); } else if (ch < 0x800) { return (2); } else if (ch < 0x10000) { return (3); } else if (ch < 0x200000) { return (4); } else if (ch < 0x4000000) { return (5); } else if (ch <= 0x7fffffff) { return (6); } return (-1); } /* * Compute # bytes that would be needed to encode an UCS-4 string in UTF-8. */ #ifdef AG_INLINE_HEADER static __inline__ int AG_LengthUTF8FromUCS4(const AG_Char *_Nonnull ucs4, AG_Size *_Nonnull rv) #else int ag_length_utf8_from_ucs4(const AG_Char *_Nonnull ucs4, AG_Size *_Nonnull rv) #endif { const AG_Char *c; int cLen; *rv = 0; for (c = &ucs4[0]; *c != '\0'; c++) { if ((cLen = AG_CharLengthUTF8FromUCS4(*c)) == -1) { return (-1); } (*rv) += cLen; } return (0); } /* * Parse the first byte of a possible UTF-8 sequence and return the length * of the sequence in bytes. Return 1 if there is no sequence. */ #ifdef AG_INLINE_HEADER static __inline__ int _Const_Attribute AG_CharLengthUTF8(unsigned char ch) #else int ag_char_length_utf8(unsigned char ch) #endif { int rv; if ((ch >> 7) == 0) { rv = 1; } else if (((ch & 0xe0) >> 5) == 0x6) { rv = 2; } else if (((ch & 0xf0) >> 4) == 0xe) { rv = 3; } else if (((ch & 0xf8) >> 3) == 0x1e) { rv = 4; } else if (((ch & 0xfc) >> 2) == 0x3e) { rv = 5; } else if (((ch & 0xfe) >> 1) == 0x7e) { rv = 6; } else { return (1); } return (rv); } /* * Return the number of characters in the given UTF-8 string, not counting * the terminating NUL. If the string is invalid, fail and return -1. */ #ifdef AG_INLINE_HEADER static __inline__ AG_Size _Pure_Attribute AG_LengthUTF8(const char *_Nonnull s) #else AG_Size ag_length_utf8(const char *s) #endif { const char *c = &s[0]; int i, cLen; AG_Size rv = 0; if (s[0] == '\0') { return (0); } for (;;) { cLen = AG_CharLengthUTF8((unsigned char)*c); for (i = 0; i < cLen; i++) { if (c[i] == '\0') return (rv); } rv++; c += cLen; } return (rv); } #endif /* AG_UNICODE */ /* * Compare two strings ignoring case. */ #ifdef AG_INLINE_HEADER static __inline__ int _Pure_Attribute AG_Strcasecmp(const char *_Nonnull s1, const char *_Nonnull s2) #else int ag_strcasecmp(const char *s1, const char *s2) #endif { const unsigned char *cm = agStrcasecmpMapASCII; const unsigned char *us1 = (const unsigned char *)s1; const unsigned char *us2 = (const unsigned char *)s2; while (cm[*us1] == cm[*us2++]) { if (*us1++ == '\0') return (0); } return (cm[*us1] - cm[*--us2]); } /* * Compare the first n characters of two strings ignoring case. */ #ifdef AG_INLINE_HEADER static __inline__ int _Pure_Attribute AG_Strncasecmp(const char *_Nonnull s1, const char *_Nonnull s2, AG_Size n) #else int ag_strncasecmp(const char *s1, const char *s2, AG_Size n) #endif { const unsigned char *cm = agStrcasecmpMapASCII; const unsigned char *us1 = (const unsigned char *)s1; const unsigned char *us2 = (const unsigned char *)s2; AG_Size i; for (i = 0; i < n; i++) { if (cm[us1[i]] != cm[us2[i]]) break; } return i == n ? 0 : cm[us1[i]] - cm[us2[i]]; }
C
#include "coder.h" void caesarclipherMut(char* string, int c) { while (*string) { if (*string >= 'c' && *string <= 'y') { if (*string + c < 'y') { *string += c; } else if (*string + c > 'y') { *string = 'c' + (*string + c) % ('y' - 'c' + 1); } else if (*string + c < 'c') { *string = 'y' - ('c' % *string) + 1; } } ++string; } } char* caesarclipherImmut(const char* string, int c) { char* result = malloc((strlen(string) + 1) * sizeof(char)); for (int i = 0; i < strlen(string); ++i) { if (string[i] >= 'c' && string[i] <= 'y') { if (*string + c < 'y') { result[i] = string[i] + c; } else if (*string + c > 'y') { result[i] = 'c' + (*string + c) % ('y' - 'c' + 1);; } else if (*string + c < 'c') { result[i] = 'y' - ('c' % (*string + c)) + 1; } } else { result[i] = string[i]; } } return result; } void XORMut(char* string, char* key) { for (int i = 0; i < strlen(string); ++i) { string[i] = string[i] ^ key[i % strlen(key)]; } char* XORImmut(const char* string, char* key) { char* result = malloc((strlen(string) + 1) * sizeof(char)) ; for (int i = 0; i <= strlen(string); ++i) { result[i] = string[i] ^ key[i % strlen(key)]; } return result; }
C
/* program, ktory pre zadane n vytvori obrazok z hviezdiciek -> piramida * ** *** **** ... */ #include <stdio.h> #include <stdlib.h> int main() { char* endp; char str[100]; printf("zadajte pocet riadkov: "); fgets(str, 100, stdin); int n = strtol(str, &endp, 10); if (*(endp+1) != 0) { printf("Zadajte cislo!\n"); return -1; } for (int i = 0; i < n; i++) { for (int j = 0; j <= i; j++) { printf("*"); } printf("\n"); } }
C
// // main.c // 05_字符串解码_leetcode_394 // // Created by SK_Wang on 2020/4/18. // Copyright © 2020 SK_Wang. All rights reserved. // #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> /* 394. 字符串解码 链接:https://leetcode-cn.com/problems/decode-string 给定一个经过编码的字符串,返回它解码后的字符串。 编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。 你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。 此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。 示例: s = "3[a]2[bc]", 返回 "aaabcbc". s = "3[a2[c]]", 返回 "accaccacc". s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef". */ /* 思路 1.遍历字符串 S 2.如果当前字符不为方括号"]" 则入栈stack中; 3.如果当前字符遇到了方括号"]" 则: 3.1 首先找到要复制的字符,例如stack="12[a",那么我要首先获取字符a;将这个a保存在另外一个栈去tempStack; 3.2 接下来,要找到需要备份的数量,例如stack="12[a",因为出栈过字符"a",则当前的top指向了"[",也就是等于2; 3.3 而12对于字符串是2个字符, 我们要通过遍历找到数字12的top上限/下限的位置索引, 此时上限curTop = 2, 下限通过出栈,top = -1; 3.4 根据范围[-1,2],读取出12保存到strOfInt 字符串中来, 并且将字符"12\0",转化成数字12; 3.5 当前top=-1,将tempStack中的字符a,复制12份入栈到stack中来; 3.6 为当前的stack扩容, 在stack字符的末尾添加字符结束符合'\0'; */ char * decodeString(char * s) { int stackSize = 50; char *stack = (char *)malloc(sizeof(char) * stackSize); int top = -1; int length = (int)strlen(s); for (int i = 0; i < length; i++) { if (s[i] != ']') { if (top == stackSize - 1) { stack = (char *)realloc(stack, (stackSize += 50) * sizeof(char)); } stack[++top] = s[i]; } else { int strStackSize = 10; char *strStack = (char *)malloc(sizeof(char) * strStackSize); int strTop = -1; while (stack[top] != '[') { if (strTop == strStackSize - 1) { strStack = (char *)realloc(strStack, sizeof(char) * (strStackSize += 10)); } strStack[++strTop] = stack[top--]; } top--; // remove '[' // char kStack[11]; // int currentTop = top; // // while (top != -1 && stack[top] >= '0' && stack[top] <= '9') { // top--; // } // // for (int j = top + 1; j < currentTop; j++) { // kStack[j - (top + 1)] = stack[j]; // } // // kStack[currentTop - (top + 1)] = '\0'; // int curNum = atoi(kStack); int curNum = 0; int j = 0; while (top != -1 && stack[top] >= '0' && stack[top] <= '9') { curNum += (stack[top] - '0') * pow(10, j++); top--; } for (int k = 0; k < curNum; k++) { int tempTop = strTop; while (tempTop != -1) { if (top == stackSize - 1) { stack = (char *)realloc(stack, sizeof(char) * (stackSize += 50)); } stack[++top] = strStack[tempTop--]; } } } } char *result = (char *)realloc(stack, sizeof(char) * (top + 2)); result[++top] = '\0'; return result; } int main(int argc, const char * argv[]) { // insert code here... printf("Hello, World!\n"); char *s ; s = decodeString("12[a]"); printf("字符编码后的结果: %s\n\n",s); return 0; }
C
#include "heap.h" Heap* create_heap(){ //creates the heap Heap *h = malloc(sizeof(Heap)); if (h == NULL) exit(-1); //creates the head of the heap h->head = malloc(sizeof(Heap_Level)); if (h->head == NULL) exit(-1); h->head->level = 1; h->head->data_array = calloc(1, sizeof(int)); if (h->head->data_array == NULL) exit(-1); h->head->next_level = NULL; h->head->prev_level = NULL; //sets heap data h->insert_level = h->head; h->insert_index = 0; return h; } int delete_heap(Heap *h){ //deletes heap h and all data within it Heap_Level *p = h->head->next_level; free(h->head->data_array); free(h->head); if(p != NULL){ while (p->next_level != NULL){ free(p->data_array); p = p->next_level; free(p->prev_level); } free(p->data_array); free(p); } free(h); return 0; } int swap(Heap_Level *al, int ai, Heap_Level *bl, int bi){ //swaps two nodes in the heap int temp = al->data_array[ai]; al->data_array[ai] = bl->data_array[bi]; bl->data_array[bi] = temp; return 0; } int up_heap(Heap *h){ Heap_Level *c_l = h->insert_level; //child level int c_i = h->insert_index; //child index Heap_Level *p_l = h->insert_level->prev_level; //parent level int p_i = c_i/2; //parent index while (p_l != NULL ){ if(c_l->data_array[c_i] <= p_l->data_array[p_i]){ swap(c_l, c_i, p_l, p_i); c_l = p_l; c_i = p_i; p_l = p_l->prev_level; p_i = c_i/2; } else break; } return 0; } int add(Heap *h, int data){ //adds the integer data into heap h h->insert_level->data_array[h->insert_index] = data; up_heap(h); int sizeof_array = (int)pow(2, h->insert_level->level-1); if (h->insert_index+1 < sizeof_array){ //if the leaf layer is not full h->insert_index++; } else{ //if the leaf layer is full and a new one needs to be added h->insert_level->next_level = malloc(sizeof(Heap_Level)); if (h->insert_level->next_level == NULL) exit(-1); h->insert_level->next_level->level = h->insert_level->level+1; h->insert_level->next_level->prev_level = h->insert_level; h->insert_level = h->insert_level->next_level; int sizeof_array = (int)pow(2, h->insert_level->level-1); h->insert_level->data_array = calloc(sizeof_array, sizeof(int)); h->insert_level->next_level = NULL; h->insert_index = 0; } return 0; } int down_heap(Heap *h){ Heap_Level *p_l = h->head; //parent level int p_i = 0; //parent index Heap_Level *c_l = h->head->next_level; //child level int lc_i = p_i*2; //left child index int rc_i = lc_i+1; //right child index while (c_l != NULL && c_l->data_array[lc_i] != 0 && c_l->data_array[rc_i] != 0){ if (p_l->data_array[p_i] >= c_l->data_array[lc_i] && c_l->data_array[rc_i] >= c_l->data_array[lc_i]){ swap(p_l, p_i, c_l, lc_i); p_i = lc_i; } else if (p_l->data_array[p_i] >= c_l->data_array[rc_i] && c_l->data_array[lc_i] >= c_l->data_array[rc_i]){ swap(p_l, p_i, c_l, rc_i); p_i = rc_i; } p_l = c_l; c_l = c_l->next_level; lc_i = p_i*2; rc_i = lc_i+1; } return 0; } int pop(Heap *h){ //pops the head of the heap h int head_data = h->head->data_array[0]; if (h->insert_index-1 >= 0){ //if the leaf layer is not empty h->insert_index--; } else{ //if the leaf layer is empty and needs to be removed h->insert_level = h->insert_level->prev_level; free(h->insert_level->next_level->data_array); free(h->insert_level->next_level); h->insert_level->next_level = NULL; h->insert_index = (int)(pow(2, h->insert_level->level-1)-1); } h->head->data_array[0] = h->insert_level->data_array[h->insert_index]; h->insert_level->data_array[h->insert_index] = 0; down_heap(h); return head_data; } int print_heap(Heap *h){ //prints inputed heap Heap_Level *p = h->head; while(p != NULL){ printf("level: %d\n", p->level); int sizeof_data_array = pow(2, p->level-1); for(int i = 0; i < sizeof_data_array; i++){ printf("%d ", *(p->data_array+i)); } printf("\n"); p = p->next_level; } return 0; }
C
/** * @file server.c * @author TEAM PINE * @brief: defines functionality for the server, * which interacts with other modules for functionality * to offer an interactive game. * @version 0.1 * @date 2021-06-01 * * @copyright Copyright (c) 2021 * */ /* standard libraries */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <ctype.h> #include <string.h> #include "file.h" /* file operations */ #include "message.h" /* message operations */ #include "log.h" /* logging operations */ #include "gamestate.h" /* gamestate module */ #include "grid.h" /* grid module */ #include "gold.h" /* gold module */ #include "player.h" /* player module */ #include "spectator.h" /* spectator module */ // Global Variables const int MaxNameLength = 50; const int MaxPlayers = 26; int GoldTotal = 250; const int GoldMinNumPiles = 10; const int GoldMaxNumPiles = 30; // Function prototypes void parseArgs(const int argc, const char* argv[], int* seed); static gamestate_t* game_init(FILE* mapfile); static void game_close(gamestate_t* gameState); void handleInput(void* arg); char** tokenize(char* message); void deleteTokens(char** parsedMessage); bool handleMessage(void* arg, const addr_t fromAddress, const char* message); void movePlayer(gamestate_t* gameState, player_t* player, int x, int y); static void handlePlayerQuit(gamestate_t* state, addr_t fromAddress); static void addSpectatorToGame(gamestate_t* state, addr_t fromAddress); static void reportMalformedMessage(addr_t fromAddress, char* givenInput, char* message); static int randomInt(int lower, int upper); static void handleSpectatorQuit(gamestate_t* state, addr_t fromAddress); static bool isGameEnded(gamestate_t* state); static void displayForSpectator(gamestate_t* state, spectator_t* spectator); static void displayForPlayer(gamestate_t* state, player_t* player); static int getRemainingGold(gamestate_t* state); static void sendGoldToPlayers(gamestate_t* state); static void sendPlayerOK(player_t* player); static void sendGoldToSpectator(gamestate_t* state); static void handleKey(gamestate_t* state, addr_t fromAddress, char pressedKey); static void playerPickedUpGold(gamestate_t* state, player_t* player, int justCollectedGold); static void endGame(gamestate_t* state); /** * @brief parses arguments * * Inputs: * @param argc: # of command line arguments * @param argv: char* array of command line arguments */ void parseArgs(const int argc, const char* argv[], int* seed) { // Check for illegal # of arguments if(argc != 3){ flog_v(stderr, "Illegal number of arguments...\n"); exit(1); } // Make sure seed is a valid number for(int i = 0; i < strlen(argv[2]); i++){ if(!isdigit(argv[2][i])){ flog_v(stderr, "Invalid seed...\n"); exit(1); } } // Set seed value *seed = atoi(argv[2]); // Try to open map file FILE* fp; if((fp = fopen(argv[1], "r")) == NULL){ flog_v(stderr, "Could not open file...\n"); exit(1); } fclose(fp); } /** * @brief constructor. Creates the gamestate object * * Inputs: * @param mapFile: a FILE pointer to the opened file containing map data. * * Returns: * @return gamestate_t*: the initialized game instance. * @return NULL: an error occured allocating memory for the gamestate. */ static gamestate_t* game_init(FILE* mapFile) { if(mapFile == NULL){ flog_v(stderr, "Unable to open and read map file\n"); exit(1); } // Create gamestate pointer and call gamestate_init() gamestate_t* gameState = gamestate_init(mapFile); // Condition: gamestate_init successfully created an object if(gameState == NULL){ // If gamestate_init gives a NULL poiter, exit with error flog_v(stderr, "Unable to allocate space for the game state.\n"); exit(1); }else{ // Distribute gold throughout the grid gold_distribute(gameState->masterGrid, gameState->gameGold); } // Return the gamestate object return gameState; } /** * @brief closer function: frees all gamestate_t associated data * * Inputs: * @param gameState: the gamestate representation of the game * */ static void game_close(gamestate_t* gameState) { if(gameState == NULL){ flog_v(stderr, "Error: GameState Null...\n"); exit(1); } else { // Close game and free memory gamestate_closeGame(gameState); } } /** * @brief Splits given string into char* array of 'tokens' * * Inputs: * @param message * * Returns: * @return char**: An array of strings (each string is a 'token'). */ char** tokenize(char* message) { if (message == NULL) { return NULL; } /* init position in tokens */ int pos = 0; /* allocate memory for char pointers, max = strlen */ char** tokens = calloc(strlen(message), sizeof(*tokens)); if (tokens == NULL) { return NULL; } char* token = strtok(message, " "); /* while next token is not NULL save it and get next token */ while (token != NULL) { tokens[pos++] = malloc(sizeof(token)+1); strcpy(tokens[pos-1], token); token = strtok(NULL, " "); } return tokens; } /** * @brief deletes array of tokens (created by tokenize earlier) * * Inputs: * @param parsedMessage: The string array of tokens * */ void deleteTokens(char** parsedMessage) { if (parsedMessage != NULL) { /* step through the tokens and free each token */ for (int i = 0; parsedMessage[i] != NULL; i++) { free(parsedMessage[i]); } /* free the holder */ free(parsedMessage); } } /** * @brief Message callback: tells server what to do with an incoming message * * Inputs: * @param arg: a pointer to the server's `gamestate` object * @param fromAddress: an addr_t representing the sending device * @param message: a string with the message text from the sender * * Returns: * @return gamestate_t*: the initialized game instance. * @return NULL: an error occured allocating memory for the gamestate. */ bool handleMessage(void* arg, const addr_t fromAddress, const char* message) { /* if any pointer arguments are NULL, return true and terminate game loop. */ if (arg == NULL || message == NULL) { flog_v(stderr, "Entered message loop without gamestate. Fatal error occurred\n"); return true; } /* convert arg back to gamestate */ gamestate_t* state = (gamestate_t*) arg; /* get tokens in message */ char* message_copy = calloc(strlen(message)+1, sizeof(*message_copy)); strcpy(message_copy, message); char** tokens; if ( (tokens = tokenize(message_copy)) != NULL) { /* find number of tokens */ int numTokens = 0; for (int i = 0; tokens[i] != NULL; i++) { numTokens = i + 1; } if (numTokens == 0) { // Send malformed message back to client / spectator message_send(fromAddress, "ERROR malformed message\n"); flog_v(stderr, "Message detected with ZERO tokens. Stop.\n"); free((char*)message); free(message_copy); free(tokens); return false; } /* run switch statement on first char of first token */ switch (tokens[0][0]) { case 'K': /* handle gameplay keys */ if (numTokens == 2 && (strcmp(tokens[0], "KEY") == 0) ) { /* call function to handle key here */ handleKey(state, fromAddress, tokens[1][0]); } else { reportMalformedMessage(fromAddress, message_copy, "is not a valid gameplay message."); } break; case 'S': /* add spectator if message checks out*/ if (numTokens == 1 && (strcmp(tokens[0], "SPECTATE") == 0) ) { /* add spectator to game */ addSpectatorToGame(state, fromAddress); } else { // Oherwise end error message to from address and log to stderr reportMalformedMessage(fromAddress, message_copy, "is not a valid add spectator message."); } break; case 'Q': /* routine for removing player */ if (numTokens == 0 && (strcmp(tokens[0], "QUIT") == 0) ) { /* if address matches spectator in the game... */ if (gamestate_isSpectator(state, fromAddress)) { // Handle spectator quit handleSpectatorQuit(state, fromAddress); } /* else --> if address doesn't match the current spectator, search for player instead. then, if, no match was found. print error message. */ else { handlePlayerQuit(state, fromAddress); } } break; case 'P': /* routine to add player */ if (numTokens >= 2 && (strcmp(tokens[0], "PLAY") == 0) ) { /* init grid for player */ grid_t* playerGrid = grid_initForPlayer(state->masterGrid); /* get number of rows and columns in master grid */ int rows = state->masterGrid->rows; int cols = state->masterGrid->cols; /* generate letter for player */ char letter = 'A' + state->players_seen; /* get full player name */ char playerName[MaxNameLength]; for (int i = 1; i < numTokens; i++) { char *temp = tokens[i]; if(i == 1){ strcpy(playerName, temp); }else{ strcat(playerName, temp); } } /* generate random x,y values and check for validity until valid point is found */ int x = randomInt(1, cols); int y = randomInt(1, rows); while (! grid_isSpace(state->masterGrid, x, y)) { x = randomInt(1, cols); y = randomInt(1, rows); } /* create player */ player_t* newPlayer = player_new(letter, playerName, fromAddress, x, y, playerGrid); /* if player created successfully, add to gamestate */ if (newPlayer != NULL) { gamestate_addPlayer(state, newPlayer); char initMessage[100]; sprintf(initMessage, "GRID %d %d", rows, cols); player_send(newPlayer, initMessage); sendPlayerOK(newPlayer); } /* if player creation failed, delete player grid print error flag */ else { grid_delete(playerGrid); reportMalformedMessage(fromAddress, message_copy, "is not a valid player message."); } } else { reportMalformedMessage(fromAddress, message_copy, "is not a valid message."); } break; } deleteTokens(tokens); //free((char*)message); free(message_copy); } // Send updated game state to spectator displayForSpectator(state, state->spectator); // Send updated game state to all players int numClients = state->players_seen; player_t** clients = state->players; for(int i = 0; i < numClients; i++){ displayForPlayer(state, clients[i]); } // Send gold to players sendGoldToPlayers(state); // Send gold to spectator sendGoldToSpectator(state); // Check if game is ended if(!isGameEnded(state)){ return false; }else{ // Do things for when game is over endGame(state); return true; } } /**************** Static Functions ******************/ /** * @brief Updates player in gamestate and sends GOLD messages * * Inputs: * @param state: the servers `gamestate` object * @param player: the player who just picked up gold * @param justCollectedGold: the amount of gold the player picked up */ static void playerPickedUpGold(gamestate_t* state, player_t* player, int justCollectedGold){ int currentPlayerGold = player->gold; int goldLeftInGame = getRemainingGold(state); // Format individual GOLD message and send to player char goldCollectedMessage[50]; sprintf(goldCollectedMessage, "GOLD %d %d %d", justCollectedGold, currentPlayerGold, goldLeftInGame); player_send(player, goldCollectedMessage); // Send GOLD messages to all players and spectators sendGoldToPlayers(state); sendGoldToSpectator(state); } /** * @brief: Function to generate a number within a range. * calls rand() to generate a random number * then bounds it to expectate range using mod operator. * This is handy because rand() doesn't take any arguments * and generates unbounded values * * @param lower: lower bound, inclusive * @param upper: upper bound, exclusive * @return int: a random value between the lower and upper bound. */ static int randomInt(int lower, int upper) { if (lower < upper) { int num = lower; int randomNumber = rand(); num += randomNumber % (upper - lower); return num; } flog_v(stderr, "Attempt to generate a number with invalid bounds. Stop.\n"); return -1; } /** * @brief constructor. * * Inputs: * @param state: the server's `gamestate` object * @param fromAddress: the address of the joining spectator * */ static void addSpectatorToGame(gamestate_t* state, addr_t fromAddress){ /* add spectator to game */ gamestate_addSpectator(state, fromAddress); /* get number of rows, columns in grid */ int rows = state->masterGrid->rows; int cols = state->masterGrid->cols; /* generate init message */ char initMessage[100]; /* No need to malloc; only used once */ sprintf(initMessage, "GRID %d %d", rows, cols); /* send init message to spectator */ spectator_send(state->spectator, initMessage); } /** * @brief logs malformed messages * * Inputs: * @param fromAddress: the address of the sending client * @param givenInput: the message the client sent * @param message: the message to log to stderr * */ static void reportMalformedMessage(addr_t fromAddress, char* givenInput, char* message){ message_send(fromAddress, "ERROR malformed message\n"); char* completeErrorMessage = calloc(1, strlen(givenInput) + strlen(message) + 10); sprintf(completeErrorMessage, "'%s' %s \n", givenInput, message); flog_s(stderr, "%s", completeErrorMessage); flog_v(stderr, "Invalid action sequence detected. Stop.\n"); free(completeErrorMessage); } /** * @brief takes care of when a spectator quits the game * * Inputs: * @param state: the server's gamestate * @param fromAddress: the address of the leaving spectator */ static void handleSpectatorQuit(gamestate_t* state, addr_t fromAddress){ /* get spectator */ spectator_t* spectator = state->spectator; /* send QUIT message to spectator */ spectator_send(spectator, "QUIT Thank you for watching!"); /* delete spectator */ spectator_delete(spectator); /* reset state spectator pointer to NULL (just so we don't get any surprises) */ state->spectator = NULL; } /** * @brief handles every possible key press from spectators and players * * Inputs: * @param state: the server's gamestate * @param fromAddress: the address of the client who send a key * @param pressedKey: the key that was pressed */ static void handleKey(gamestate_t* state, addr_t fromAddress, char pressedKey){ // Get player object from address player_t* player = gamestate_findPlayerByAddress(state, fromAddress); grid_t* Grid = state->masterGrid; // If cant find player but can find spectator if (player == NULL && message_eqAddr(fromAddress, state->spectator->address) ){ flog_v(stderr, "Couldn't find a matching player for key press\n"); if (pressedKey == 'Q'){ handleSpectatorQuit(state, fromAddress); } return; } switch (pressedKey) { case 'l': movePlayer(state, player, player->x+1, player->y); break; case 'h': movePlayer(state, player, player->x-1, player->y); break; case 'k': movePlayer(state, player, player->x, player->y-1); break; case 'j': movePlayer(state, player, player->x, player->y+1); break; case 'u': movePlayer(state, player, player->x+1, player->y-1); break; case 'y': movePlayer(state, player, player->x-1, player->y-1); break; case 'b': movePlayer(state, player, player->x-1, player->y+1); break; case 'n': movePlayer(state, player, player->x+1, player->y+1); break; case 'L': while(!grid_isWall(Grid, player->x+1, player->y)){ movePlayer(state, player, player->x+1, player->y); } break; case 'H': while(!grid_isWall(Grid, player->x-1, player->y)){ movePlayer(state, player, player->x-1, player->y); } break; case 'K': while(!grid_isWall(Grid, player->x, player->y-1)){ movePlayer(state, player, player->x, player->y-1); } break; case 'J': while(!grid_isWall(Grid, player->x, player->y+1)){ movePlayer(state, player, player->x, player->y+1); } break; case 'U': while(!grid_isWall(Grid, player->x+1, player->y-1)){ movePlayer(state, player, player->x+1, player->y-1); } break; case 'Y': while(!grid_isWall(Grid, player->x-1, player->y-1)){ movePlayer(state, player, player->x-1, player->y-1); } break; case 'B': while(!grid_isWall(Grid, player->x-1, player->y+1)){ movePlayer(state, player, player->x-1, player->y+1); } break; case 'N': while(!grid_isWall(Grid, player->x+1, player->y+1)){ movePlayer(state, player, player->x+1, player->y+1); } break; case 'Q': handlePlayerQuit(state, fromAddress); break; default: break; } } /** * @brief handles the case when a player quits the game * * Inputs: * @param gamestate: the server's gamestate * @param fromAddress: the address of the quitting player */ static void handlePlayerQuit(gamestate_t* state, addr_t fromAddress){ /* We don't actually delete the player from the game because we need to keep their information until end of game. */ // Search for player with matching address in gamestate player_t* player = gamestate_findPlayerByAddress(state, fromAddress); // If we find a matching player in the game, let them quit if (player != NULL) { player->hasQuit = true; player_send(player, "QUIT Thank you for playing!"); } /* if the search function returns NULL, no player was found. print to stderr. */ else { flog_v(stderr, "No matching player OR spectator found for an incoming QUIT message.\n"); } } /** * @brief Sends the DISPLAY message to the spectator * * Inputs: * @param state: the server's gamestate * @param spectator: a pointer to the spectator to send to */ static void displayForSpectator(gamestate_t* state, spectator_t* spectator){ // Convert master grid to a string grid_t* entireGrid = state->masterGrid; char* masterGridAsString = grid_toString(state, entireGrid); // Create message header char* messageHeader = malloc((sizeof(char) * strlen(masterGridAsString)) + 10 ); // Concatenate and send message strcpy(messageHeader, "DISPLAY\n"); strcat(messageHeader, masterGridAsString); spectator_send(spectator, messageHeader); // Free created memory free(messageHeader); free(masterGridAsString); } /** * @brief sends the display method to the player. * * Inputs: * @ * * Returns: * @return gamestate_t*: the initialized game instance. * @return NULL: an error occured allocating memory for the gamestate. */ static void displayForPlayer(gamestate_t* state, player_t* player){ // Update player's visible grid grid_t* entireGrid = state->masterGrid; grid_calculateVisibility(entireGrid, player); // Covert visible grid to string char* playerGridAsString = grid_toStringForPlayer(state, player); // Create message header char* messageHeader = malloc((sizeof(char) * strlen(playerGridAsString)) + 10 ); strcpy(messageHeader, "DISPLAY\n"); /* TODO: Make a playerSpecific grid_toString function that takes in * the game state so that player and gold visibility can be accounted for * in the final string. */ strcat(messageHeader, playerGridAsString); player_send(player, messageHeader); // Free created memory free(messageHeader); free(playerGridAsString); } static bool isGameEnded(gamestate_t* state){ // Get gold object from game state gold_t* gold_from_state = state->gameGold; // See if we have collected all gold piles // (if index == num_gold_piles) int index = gold_from_state->index; int num_gold_piles = gold_from_state->numPiles; if(index >= num_gold_piles){ return true; } else{ return false; } } void movePlayer(gamestate_t* gameState, player_t* player, int x, int y){ if(gameState == NULL){ return; } if(x < 0 || y < 0|| x >= gameState->masterGrid->cols || y >= gameState->masterGrid->rows){ return; } grid_t* Grid = gameState->masterGrid; gold_t* gameGold = gameState->gameGold; char** player_grid = player->grid->g; char** master_grid = Grid->g; int* gold_array = gameGold->goldCounter; player_t **players = gameState->players; player_t* otherPlayer = NULL; for(int i = 0; i < gameState->players_seen;i++){ otherPlayer = players[i]; if (otherPlayer->x == x && otherPlayer->y == y && otherPlayer->letter != player->letter){ break; } else{ otherPlayer = NULL; } } if(!grid_isWall(Grid, x, y)){ if (grid_isGold(Grid, x, y)){ player_grid[player->y][player->x] = '.'; master_grid[player->y][player->x] = '.'; player->x = x; player->y = y; player->gold += gold_array[gameGold->index]; int goldJustCollected = gold_array[gameGold->index]; playerPickedUpGold(gameState, player, goldJustCollected); gameGold->index += 1; master_grid[player->y][player->x] = '.'; player_grid[player->y][player->x] = '.'; }else if(otherPlayer != NULL){ char** otherPlayer_grid = otherPlayer->grid->g; int tempx = player->x; int tempy = player->y; player_grid[player->y][player->x] = master_grid[player->y][player->x]; otherPlayer_grid[otherPlayer->y][otherPlayer->x] = master_grid[otherPlayer->y][otherPlayer->x]; player->y = otherPlayer->y; player->x = otherPlayer->x; otherPlayer->y = tempy; otherPlayer->x = tempx; }else{ player_grid[y][x] = master_grid[y][x]; player->x = x; player->y = y; } } } static void endGame(gamestate_t* state){ // Get array of players and length of players array player_t** allPlayers = state->players; int numPlayers = state->players_seen; // Allocate space for message to players char* endMessage = calloc(1+numPlayers, (MaxNameLength*sizeof(char)) + 20); // Loop over every player and add info to leaderboard strcpy(endMessage, "QUIT GAME OVER:\n"); for(int i = 0; i < numPlayers; i++){ char* tempBuffer = calloc(1, (MaxNameLength*sizeof(char)) + 20); // Concatenate new player info onto leaderboard sprintf(tempBuffer, "%c %d %s\n", allPlayers[i]->letter, allPlayers[i]->gold, allPlayers[i]->name); strcat(endMessage, tempBuffer); // Free associated memory free(tempBuffer); } // Send message to all players and the specatator and then free them for(int i = 0; i < numPlayers; i++){ player_send(allPlayers[i], endMessage); } spectator_send(state->spectator, endMessage); // Free ending message free(endMessage); } static void sendGoldToPlayers(gamestate_t* state){ // Loop over every player player_t** allPlayers = state->players; int numPlayers = state->players_seen; for(int i = 0; i < numPlayers; i++){ // Get n, p and r int currentPlayerGold = allPlayers[i]->gold; int justCollectedGold = 0; int goldLeftInGame = getRemainingGold(state); // Format and send message char* goldMessage = malloc(sizeof(char) * 100); sprintf(goldMessage, "GOLD %d %d %d", justCollectedGold, currentPlayerGold, goldLeftInGame); player_send(allPlayers[i], goldMessage); // Free used memory free(goldMessage); } } static void sendGoldToSpectator(gamestate_t* state){ // Get spectator object spectator_t* spectator = state->spectator; // Get numbers for amnt of gold int currentGold = 0; int justCollectedGold = 0; int goldLeftInGame = getRemainingGold(state); // Create gold message char* goldMessage = malloc(sizeof(char) * 100); sprintf(goldMessage, "GOLD %d %d %d", currentGold, justCollectedGold, goldLeftInGame); // Send gold message spectator_send(spectator, goldMessage); //Free created memory free(goldMessage); } static int getRemainingGold(gamestate_t* state){ gold_t* gamestateGold = state->gameGold; int goldLeft = 0; int currentIndex = gamestateGold->index; for(int i = currentIndex; i < gamestateGold->numPiles; i++){ goldLeft += gamestateGold->goldCounter[i]; } return goldLeft; } static void sendPlayerOK(player_t* player){ // Generate message from player data char okMessage[10]; sprintf(okMessage, "OK %c", player->letter); // Send message to player player_send(player, okMessage); } int main(const int argc, const char* argv[]) { // Parse arguments and use seed value int seed = 0; parseArgs(argc, argv, &seed); srand(seed); // Open and close map file and init gamestate object FILE* fp = fopen(argv[1], "r"); gamestate_t* gs = game_init(fp); if(gs == NULL){ printf("NULL GAMESTATE!\n"); exit(1); } fclose(fp); // Initialize network and get port number int port = message_init(stderr); if(port == 0){ flog_v(stderr, "Could not initialize message...\n"); exit(1); } // Start message loop message_loop( gs, /* Argument passed to all callbacks */ 0.0,/* Timeout specifier (0 in our case) */ NULL,/* Handle Timeout function pointer (NULL in our case) */ NULL, /* Handle stdin (NULL in our case) */ handleMessage ); // Free all gamestate memory game_close(gs); flog_done(stderr); }
C
#include<stdio.h> int main() { int i=12,*ip=&i; double d =2.3,*dp=&d; char ch='a',*cp=&ch; printf("Value of ip= %p \n",ip); printf("Value of dp= %p \n",dp); printf("Value of cp= %p \n\n",cp); printf("Value of ip+1= %p \n",ip+1); printf("Value of dp+1= %p \n",dp+1); printf("Value of cp+1= %p \n\n",cp+1); printf("Value of ip+2= %p \n",ip+2); printf("Value of dp+2= %p \n",dp+2); printf("Value of cp+2= %p \n",cp+2); return(0); }
C
/* ** EPITECH PROJECT, 2019 ** Makefile ** File description: ** Makefile */ #include "warlock.h" /* \fn char **clean_double_alloc(int y, int x) \brief allocate array of string in desirated size. \param y : the number of string \param x : the lenght of each string \return a new array of string(char **). */ char **clean_double_alloc(int y, int x) { char **double_buffer = NULL; double_buffer = malloc(sizeof(char *) * (y + 1)); if (double_buffer == NULL) { put_error("allocation error !\n"); return (NULL); } for (int i = 0; i < y; i++) { double_buffer[i] = NULL; double_buffer[i] = clean_alloc(x); if (double_buffer[i] == NULL) { put_error("allocation error !\n"); return (NULL); } } double_buffer[y] = NULL; return (double_buffer); }
C
#include<stdio.h> #include<conio.h> void main() { int n,k,a; printf("enter the 1st no"); scanf("%d",&n); printf("enter the 2nd no"); scanf("%d",&k); a=n+k; if(a%2==0) { printf("even"); } else { printf("odd"); } }
C
#ifndef _es_math_utils_h_ #define _es_math_utils_h_ ES_DECL_EXPORTED_REFLECTED_SERVICES_BEGIN( EsMath, ESMATH_CLASS ) /// Reflected math constants /// /// PI ES_DECL_REFLECTED_CLASS_METHOD0(double, pi); /// 2*PI ES_DECL_REFLECTED_CLASS_METHOD0(double, _2pi); /// PI/2 ES_DECL_REFLECTED_CLASS_METHOD0(double, pi_2); /// PI/180 ES_DECL_REFLECTED_CLASS_METHOD0(double, pi_180); /// e ES_DECL_REFLECTED_CLASS_METHOD0(double, e); /// Reflected validity check functions /// /// Is infinite float check ES_DECL_REFLECTED_CLASS_METHOD1(bool, isInf, double); /// Is NAN float check ES_DECL_REFLECTED_CLASS_METHOD1(bool, isNaN, double); /// Comparison /// /// Double internals-aware equality comparison. Comparison accuracy used is 1 ULPs /// (Units in the Last Place) /// ES_DECL_REFLECTED_CLASS_METHOD2(bool, areEqualFloats, double, double); /// Double internals-aware equality comparison, an additional parameter /// is comparison accuracy, in ULPs (Units in the Last Place) /// ES_DECL_REFLECTED_CLASS_METHOD3(bool, areEqualFloats, double, double, ulong); /// Reflected standard math functions /// /// Effective 10^n calculation ES_DECL_REFLECTED_CLASS_METHOD1(double, pow10, long); /// Effective 2^n calculation ES_DECL_REFLECTED_CLASS_METHOD1(double, pow2, long); /// n^m calculation powNM(n, m) ES_DECL_REFLECTED_CLASS_METHOD2(double, powNM, double, double); /// e^m calculation exp(m) ES_DECL_REFLECTED_CLASS_METHOD1(double, exp, double); /// Square root sqrt(val) ES_DECL_REFLECTED_CLASS_METHOD1(double, sqrt, double); /// Round the floating number, using the number of the floating point digits /// after comma. Note that the function can yield imprecise result. /// If numDecimalPlaces is zero, the behavior is equivalent to Round0. /// /// Here is the usage: /// double x = EsMath::round(0.555, 1); // 0.6 /// double y = EsMath::round(1.234567, 2); // 1.23 /// ES_DECL_REFLECTED_CLASS_METHOD2(double, round, double, ulong); /// Same as above, but use 0 as decimal places count, effectively rounding to interal ES_DECL_REFLECTED_CLASS_METHOD1(double, round, double); /// Convert deg to rad and vice versa ES_DECL_REFLECTED_CLASS_METHOD1(double, degToRad, double); ES_DECL_REFLECTED_CLASS_METHOD1(double, radToDeg, double); /// Split floating point argument into fractional and integer parts. /// Returned is [int, frac] /// ES_DECL_REFLECTED_CLASS_METHOD1(EsVariant, modf, double); /// Absolute value of argument ES_DECL_REFLECTED_CLASS_METHOD1(double, abs, double); /// Natural logarithm ES_DECL_REFLECTED_CLASS_METHOD1(double, log, double); /// 2-base logarithm ES_DECL_REFLECTED_CLASS_METHOD1(double, log2, double); /// 10-base logarithm ES_DECL_REFLECTED_CLASS_METHOD1(double, log10, double); /// N-base logarithm logN(base, val) ES_DECL_REFLECTED_CLASS_METHOD2(double, logN, double, double); /// Sine sin(rad) ES_DECL_REFLECTED_CLASS_METHOD1(double, sin, double); /// Hyperbolic sine sinh(rad) ES_DECL_REFLECTED_CLASS_METHOD1(double, sinh, double); /// Arc sine asin(val) ES_DECL_REFLECTED_CLASS_METHOD1(double, asin, double); /// Cosine cos(rad) ES_DECL_REFLECTED_CLASS_METHOD1(double, cos, double); /// Hyperbolic cosine cosh(rad) ES_DECL_REFLECTED_CLASS_METHOD1(double, cosh, double); /// Arc cosine acos(val) ES_DECL_REFLECTED_CLASS_METHOD1(double, acos, double); /// Tangent tan(rad) ES_DECL_REFLECTED_CLASS_METHOD1(double, tan, double); /// Hyperbolical tangent tanh(rad) ES_DECL_REFLECTED_CLASS_METHOD1(double, tanh, double); /// Arc tangent atan(val) ES_DECL_REFLECTED_CLASS_METHOD1(double, atan, double); /// Arc tangent of Y/X atanYX(y, x) ES_DECL_REFLECTED_CLASS_METHOD2(double, atanYX, double, double); /// GEO-specific math /// /// Distance estimate in meters between lat1,lon1 .. lat2,lon2 ES_DECL_REFLECTED_CLASS_METHOD4(double, geoDistanceEstimate, double, double, double, double); /// Fast distance estimate in meters between lat1,lon1 .. lat2,lon2 ES_DECL_REFLECTED_CLASS_METHOD4(double, geoDistanceEstimateFast, double, double, double, double); /// Bearing between two points, in degrees ES_DECL_REFLECTED_CLASS_METHOD4(double, geoBearing, double, double, double, double); /// Algorithms /// /// Calculate the first derivative of an input vector|numeric collection ES_DECL_REFLECTED_CLASS_METHOD1(EsVariant, diff, cr_EsVariant); /// @brief Calculate sum of an input vector|numeric collection /// /// @param p1 [in] Either collection of convertibles to numeric, or EsMathArrayReal object. /// @return Accumulated sum, or an empty variant, if input is empty /// ES_DECL_REFLECTED_CLASS_METHOD1(EsVariant, accumulate, cr_EsVariant); /// Non-reflected stuff /// /// Complex value type /// struct Complex { Complex(double re = 0, double im = 0) : m_re(re), m_im(im) {} double m_re; double m_im; }; /// Directly accessible math constants /// static const double c_pi; static const double c_2pi; static const double c_pi_2; static const double c_pi_180; static const double c_e; ES_DECL_REFLECTED_SERVICES_END #endif // _es_math_utils_h_
C
// SPDX-License-Identifier: LGPL-2.1-or-later /* * Copyright (C) 2008-2020 Cyril Hrubis <metan@ucw.cz> */ /* * Evfilter dump: * * Writes nice decomposition of event to the FILE. * * parameters: * * prefix = string * prefix that is printed in every print * * file = path * path to file to print to, there are two special files stdout and stderr */ #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <linux/input.h> #include "evf_input.h" #include "filter.h" #include "filters.h" struct dump { FILE *f; char prefix[]; }; static void dump_process(struct evf_filter *self, struct input_event *ev) { struct dump *dump = (struct dump*) self->data; evf_input_print(dump->f, dump->prefix, ev); fprintf(dump->f, "\n"); evf_filter_process(self->next, ev); } static struct evf_filter *dump_from_json(json_object *json_data) { FILE *f = NULL; const char *fname = NULL; const char *prefix = ""; json_object_object_foreach(json_data, key, val) { if (!strcmp(key, "file")) { fname = json_object_get_string(val); if (!strcmp(fname, "stdout")) f = stdout; else if (!strcmp(fname, "stderr")) f = stderr; else f = fopen(fname, "w"); } else if (!strcmp(key, "prefix")) { prefix = json_object_get_string(val); } else { evf_msg(EVF_DEBUG, "Invalid JSON dump filter key %s", key); return NULL; } } if (!fname) f = stdout; if (!f) { evf_msg(EVF_ERR, "Failed to open '%s': %s", fname, strerror(errno)); return NULL; } return evf_dump_alloc(prefix, f); } struct evf_filter_ops evf_dump_ops = { .json_id = "dump", .from_json = dump_from_json, .process = dump_process, .desc = "Dumps human readable decomposition of the events into a file", }; struct evf_filter *evf_dump_alloc(const char *prefix, FILE *f) { struct evf_filter *filter; struct dump *tmp; filter = evf_filter_alloc("dump", sizeof(struct evf_filter) + sizeof(struct dump) + strlen(prefix) + 1); if (!filter) return NULL; filter->ops = &evf_dump_ops; tmp = (struct dump*)filter->data; strcpy(tmp->prefix, prefix); tmp->f = f; return filter; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/types.h> #include <unistd.h> #include <errno.h> #define SERV_PORT 4507 #define LISTENQ 12 #define INVALID_USERINFO 'n' #define VALID_USERINFO 'y' #define USERNAME 0 #define PASSWORD 1 struct userinfo { char username[32]; char password[32]; }; struct userinfo users[] = {{"linux", "unix"}, {"4507", "4508"}, {"clh", "clh"}, {" ", " "}}; void err(const char *string, int line) { perror(string); printf("line : %d", line); exit(0); } int find_name(const char *name) { int i; if(name == NULL){ printf("in find_name, NULL pointer\n"); return -2; } for(i = 0; users[i].username[0] != 0; i++) if(!strcmp(users[i].username, name)) return i; return -1; } void send_data(int conn_fd, const char *string) { if(send(conn_fd, string, sizeof(string), 0) < 0) err("send", __LINE__); } int main (void) { int sock_fd, conn_fd; int optval, ret, pid, cli_len, name_num; int flag_recv = USERNAME; struct sockaddr_in cli_addr, serv_addr; char recv_buf[128]; sock_fd = socket(AF_INET, SOCK_STREAM, 0); if(sock_fd < 0) err("socket", __LINE__); optval = 1; if(setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, (void *)&optval, sizeof(int)) < 0) err("setsockopt", __LINE__); memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(SERV_PORT); serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); if(bind(sock_fd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr_in)) < 0) err("bind", __LINE__); if(listen(sock_fd, LISTENQ) < 0) err("listen", __LINE__); cli_len = sizeof(struct sockaddr_in); while(1) { conn_fd = accept(sock_fd, (struct sockaddr *)&cli_addr, &cli_len); if(conn_fd < 0) err("accept", __LINE__); printf("accept a new client, ip: %s\n", inet_ntoa(cli_addr.sin_addr)); if((pid = fork()) == 0) { while(1) { if((ret = recv(conn_fd, recv_buf, sizeof(recv_buf), 0)) < 0) err("recv", __LINE__); recv_buf[ret - 1] = 0; if(flag_recv == USERNAME) { name_num = find_name(recv_buf); switch(name_num) { case -1: send_data(conn_fd, "n\n"); break; case -2: exit(1); default: send_data(conn_fd, "y\n"); flag_recv = PASSWORD; break; } } else if(flag_recv == PASSWORD) { if(!strcmp(users[name_num].password, recv_buf)) { send_data(conn_fd, "y\n"); send_data(conn_fd, "Welcome to my tcp server.\n"); printf("%s login\n", users[name_num].username); break; } else send_data(conn_fd, "n\n"); } } close(sock_fd); close(conn_fd); exit(0); } else close(conn_fd); } return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <unistd.h> #include <signal.h> #include <sys/types.h> #include <sys/socket.h> #include <errno.h> #include "util_socket.h" #define MAX_STR_LEN 1024 /* prototypes */ static void sigIntHandler(int sig); static void connection_handler(); static ssize_t recvline(int fd, char* buf, size_t buf_len); static ssize_t sendbuf(int fd, const char* buf, size_t buf_len); /* globals */ int socket_listen = -1; int socket_conn = -1; /* main entry point */ int main(int argc, char* argv[]) { short port = -1; char* endptr = NULL; /* command line arguments */ if (argc == 2) { port = strtol(argv[1], &endptr, 0); if (*endptr) { fprintf(stderr, "Invalid port number.\n"); exit(EXIT_FAILURE); } } else { fprintf(stderr, "Usage: %s <port-number>\n", argv[0]); exit(EXIT_FAILURE); } /* signal handler to shutdown clearly */ if (signal(SIGINT, sigIntHandler) == SIG_ERR) { perror("signal"); exit(EXIT_FAILURE); } socket_listen = setup_socket(port); /* wait for connections */ for (;;) { if ((socket_conn = accept(socket_listen, NULL, NULL)) < 0) { perror("accept"); exit(EXIT_FAILURE); } connection_handler(); } return EXIT_SUCCESS; } static void sigIntHandler(int sig) { fprintf(stderr, "Shutting down ... \n"); if (socket_listen != -1) { close(socket_listen); } if (socket_conn != -1) { close(socket_conn); } exit(EXIT_SUCCESS); } static void connection_handler() { char buffer[MAX_STR_LEN] = { '\0' }; unsigned cnt = -1; ssize_t num_bytes_read = 0; /* handle connections */ for (;;) { num_bytes_read = recvline(socket_conn, buffer, MAX_STR_LEN); if (num_bytes_read < 0) { fprintf(stderr, "Could not read line. Ignoring client. \n"); /* exit(EXIT_FAILURE); */ break; } else if (num_bytes_read == 0) { fprintf(stderr, "Client has closed connection. \n"); break; } else { for (cnt = 0; cnt < strlen(buffer); cnt++) { buffer[cnt] = toupper(buffer[cnt]); } if (sendbuf(socket_conn, buffer, strlen(buffer)) < 0) { fprintf(stderr, "Could not write line.\n"); /* exit(EXIT_FAILURE); */ break; } } } /* close connection to client */ if (close(socket_conn) < 0) { fprintf(stderr, "Error during close(2). \n"); exit(EXIT_FAILURE); } buffer[0] = '\0'; socket_conn = -1; } static ssize_t recvline(int fd, char* buf, size_t buf_len) { size_t cnt = 0; ssize_t rc = 0; char* buf_ptr = buf; char c = '\0'; for (cnt = 1; cnt < buf_len; cnt++) { if ((rc = recv(fd, &c, 1, 0) > 0)) { *buf_ptr = c; buf_ptr++; if (c == '\n') { break; } } else if (rc == 0) { if (cnt == 1) { return 0; } else { break; } } else { if (errno == EINTR) { continue; } fprintf(stderr, "Error during recv(2).\n"); exit(EXIT_FAILURE); } } *buf_ptr = '\0'; return cnt; } static ssize_t sendbuf(int fd, const char* buf, size_t buf_len) { size_t chars_left = buf_len; ssize_t chars_written = 0; const char* buf_ptr = buf; while (chars_left > 0) { if ((chars_written = send(fd, buf, chars_left, 0)) <= 0) { if (errno == EINTR) { chars_written = 0; } else { fprintf(stderr, "Error during send(2). \n"); return -1; } } chars_left -= chars_written; buf_ptr += chars_written; } return buf_len; }
C
#include <stdio.h> int pow2(int n); int main(int argc, char const *argv[]) { int n = 9; for (int i = 0; i <= n; ++i) { printf("%d ", pow2(i)); } puts("\n"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "pipeStructs.c" #define MAXPENDING 5 void DieWithError( char *errorMessage ); void comm(void* threadArgs) { int n, nbytes; char buffer[256]; bzero(buffer,256); struct sock_pipe *foo; foo = (struct sock_pipe *) threadArgs; int listenPipe = foo->listenPipe; int talkPipe = foo->talkPipe; int sock = foo->sock; printf("establishing connection on socket %d\n", sock); while(1) { n = read(foo.sock,buffer,255); if (n < 0) printf("ERROR reading from socket"); write(talkPipe, sock, sizeof(buffer)); nbytes = read(listenPipe, buffer, sizeof(buffer)); printf("Here is the message on socket %d: %s\n", buffer, foo.sock); n = write(nbytes,"I got your message",18); if (n < 0) printf("ERROR writing to socket"); } exit(1); }
C
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <cv.h> #include <highgui.h> int main(int argc, char *argv[]) { IplImage* img = 0; int height,width,step,channels; uchar *data; int i,j,k; if(argc<2){ printf("Usage: main <image-file-name>\n\7"); exit(0); } // load an image img=cvLoadImage(argv[1], 0); if(!img){ printf("Could not load image file: %s\n",argv[1]); exit(0); } // get the image data height = img->height; width = img->width; step = img->widthStep; channels = img->nChannels; data = (uchar *)img->imageData; printf("Processing a %dx%d image with %d channels\n",height,width,channels); IplImage *smoothImg = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1); IplImage *sobelImg = cvCreateImage(cvSize(width, height), IPL_DEPTH_16S, 1); IplImage *binaryImg = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1); IplImage *adThresImg = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1); cvSmooth(img, smoothImg, CV_MEDIAN, 3, 0, 0, 0); cvThreshold(smoothImg, binaryImg, atoi(argv[4]), 255, CV_THRESH_BINARY); double max_value = 255; int adpative_method=CV_ADAPTIVE_THRESH_GAUSSIAN_C;//CV_ADAPTIVE_THRESH_MEAN_C int threshold_type=CV_THRESH_BINARY; int block_size=atoi(argv[2]); int offset=atoi(argv[3]); cvAdaptiveThreshold(smoothImg,adThresImg,max_value,adpative_method,threshold_type,block_size,offset); cvSobel(smoothImg, sobelImg, 1, 1, 3); // create a window // cvNamedWindow("mainWin", CV_WINDOW_AUTOSIZE); // cvMoveWindow("mainWin", 100, 100); // cvShowImage("mainWin", smoothImg); // cvNamedWindow("sobel", CV_WINDOW_AUTOSIZE); // cvShowImage("sobel", sobelImg); cvNamedWindow("thres", CV_WINDOW_AUTOSIZE); cvShowImage("thres", adThresImg); // cvNamedWindow("binary", CV_WINDOW_AUTOSIZE); // cvShowImage("binary", binaryImg); // wait for a key cvWaitKey(0); cvSaveImage("a.jpg", adThresImg, 0); // release the image cvReleaseImage(&img ); return 0; }
C
/* Fred Mapper is considering purchasing some land in Louisiana to build his house on. In the process of investigating the land, he learned that the state of Louisiana is actually shrinking by 50 square miles each year, due to erosion caused by the Mississippi River. Since Fred is hoping to live in this house the rest of his life, he needs to know if his land is going to be lost to erosion. After doing more research, Fred has learned that the land that is being lost forms a semicircle. This semicircle is part of a circle centered at (0,0), with the line that bisects the circle being the X axis. Locations below the X axis are in the water. The semicircle has an area of 0 at the beginning of year 1. (Semicircle illustrated in the Figure.) */ #include<stdio.h> int main() { double pi=3.14159265358979; int year = 0,n,i; double x,y; scanf("%d",&n); for(i=0;i<n;i++){ scanf("%lf%lf",&x,&y); year = (int)(pi*(x*x+y*y)/100.0)+1; printf("Property %d: This property will begin eroding in year %d.\n",i+1,year); } printf("END OF OUTPUT.\n"); return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> static void loadSize (char * filename, int * n, int * m){ FILE * fp = fopen(filename, "rb"); int num[2] = {0,0}; fread(num, sizeof(int), 2, fp); int cols = num[0]; int rows = num[1]; *n = cols; *m = rows; fclose(fp); } static void loadFile (char * filename, int cols, int rows, int ** seqs){ FILE * fp = fopen(filename, "rb"); int num[2] = {0,0}; fread(num, sizeof(int), 2, fp); int i = 0; int j = 0; for(i = 0; i < rows; i++){for(j = 0; j < cols; j++) {fread(&seqs[i][j], sizeof(int), 1, fp);}} fclose(fp); } static int checkSeq(int ** seqs, int * curTop_posn, int curMax, int * max, int * maxSeq, int cols, int rows){ int s1_curNum = seqs[0][curTop_posn[0]]; int found = 0; int i = 0; int j = 0; int * nextTop_posn = malloc(sizeof(int) * cols); for(i = 1; i < rows; i++){ if(curTop_posn[i] > cols){ free(nextTop_posn); return 0; } found = 0; for(j = curTop_posn[i]; (j < cols) && (found == 0); j++){ if(seqs[i][j] == s1_curNum){ found = 1; nextTop_posn[i] = j+1; } } if(found == 0){ free(nextTop_posn); return 0; } } //UPDATE MAX curMax = curMax + 1; int maxChanged = 0; if(curMax > *max){ *max = curMax; maxChanged = 1; } for(nextTop_posn[0] = curTop_posn[0] + 1; nextTop_posn[0] < cols; nextTop_posn[0]++){ if(checkSeq(seqs, nextTop_posn, curMax, max, maxSeq, cols, rows)){maxChanged = 1;} } if(maxChanged){maxSeq[curMax - 1] = s1_curNum;} free(nextTop_posn); return maxChanged; } int * Longest_conserved_gene_sequence (char * filename, int * size_of_seq){ //Check file FILE *file = NULL; if ((file = fopen(filename, "rb"))){ fclose(file); } else{ * size_of_seq = 0; return NULL; } //load the value of row and column int n = 0; int m = 0; loadSize (filename, &n, &m); if(m > 10000 || n > 100000){ * size_of_seq = 0; return NULL; } //create and fill sequences matrix int ** seqs = malloc(sizeof(int *) * m); int i = 0; for(i = 0; i < m; i++){seqs[i] = malloc(sizeof(int) * n);} int rows = m; int cols = n; loadFile(filename, cols, rows, seqs); //find longest subsequence int * curTop_posn = malloc(sizeof(int) * cols); int * maxSeq = malloc(sizeof(int) * cols); for(i = 0; i < cols; i++){ curTop_posn[i] = 0; maxSeq[i] = 0; } int curMax = 0; int max = 0; for(i = 0; i < cols; i++){ curTop_posn[0] = i; checkSeq(seqs, curTop_posn, curMax, &max, maxSeq, cols, rows); } int * longestSeq = malloc(sizeof(int) * (max)); for(i = 0; i < max; i++){longestSeq[i] = maxSeq[i];} //FREE VARIABLES free(maxSeq); free(curTop_posn); for(i = 0; i < m; i++){free(seqs[i]);} free(seqs); *size_of_seq = max; return longestSeq; }
C
#include <stdio.h> #include <stdlib.h> #include "env_set.h" #include "utils.h" /* * This function creates a new node for the list with the string * formatted as "key=value". */ t_env *new_env(const char *str) { int i; t_env *ret; ret = (t_env *)malloc(sizeof(t_env)); if (!ret) return (0); i = 0; ret->next = 0; ret->value = 0; while (str[i] && str[i] != '=') i++; ret->key = ft_strndup(str, i); if (!ret) ft_free(ret); if (str[i] == '=') { ret->value = ft_strdup(str + i + 1); if (!ret->value) return (ft_dummy((int)ft_free(ret->key) + (int)ft_free(ret))); } return (ret); } /* * This function returns a new node for the list with the key and the * value passed. */ t_env *new_env2(const char *key, const char *value) { t_env *ret; char *keycpy; char *valuecpy; if (!key) return (0); ret = (t_env *)malloc(sizeof(t_env)); if (!ret) return (0); keycpy = ft_strdup(key); if (!keycpy) return (ft_free(ret)); valuecpy = 0; if (value) { valuecpy = ft_strdup(value); if (!value) return (ft_dummy((int)ft_free(keycpy) + (int)ft_free(ret))); } ret->key = keycpy; ret->value = valuecpy; ret->next = 0; return (ret); } /* * This function creates a new list of variables directly from * a array of strings such the one in the main function in which each * string is "key=value". */ t_env *env_init(const char *str[]) { int i; t_env *aux; t_env *ret; t_env *prev; i = 0; ret = 0; prev = 0; while (str[i]) { aux = new_env(str[i]); if (!aux) return (0); if (!ret) ret = aux; if (prev) prev->next = aux; prev = aux; i++; } return (ret); } /* * This function adds the passed node tho the list, * if the key already existed in the list the value is overwritten * and the passed node is freed. */ void env_add(t_env *start, t_env *e) { t_env *tmp; tmp = start; while (tmp) { if (!ft_strcmp(tmp->key, e->key)) { if (tmp->value && e->value) free (tmp->value); if (e->value) tmp->value = e->value; free(e->key); free (e); return ; } if (!tmp->next) break ; tmp = tmp->next; } tmp->next = e; } /* * This function deletes from the list of variables * the node containing the key passed. */ void env_delete(t_env **start, const char *key) { t_env *tmp; t_env *prev; tmp = *start; prev = 0; while (tmp) { if (!ft_strcmp(tmp->key, key)) { if (!prev) *start = tmp->next; else prev->next = tmp->next; free(tmp->key); free(tmp->value); free(tmp); break ; } prev = tmp; tmp = tmp->next; } }
C
#include <stdio.h> int main(){ int n; int voti [5][5]; for(int i=0; i<5; i++){ for(int j=0; j<5; j++){ scanf("%d ", &n); voti[i][j]=n; } } float esame1, esame2, esame3, esame4, esame5; float studente1, studente2, studente3, studente4, studente5; for(int k=0; k<5; k++){ esame1= esame1+ voti[k][0]; } esame1= esame1/5; printf("%.2f \n", esame1); for(int k=0; k<5; k++){ esame2= esame2+ voti[k][1]; } esame2= esame2/5; printf("%.2f \n", esame2); for(int k=0; k<5; k++){ esame3= esame3+ voti[k][2]; } esame3= esame3/5; printf("%.2f \n", esame3); for(int k=0; k<5; k++){ esame4= esame4+ voti[k][3]; } esame4= esame4/5; printf("%.2f \n", esame4); for(int k=0; k<5; k++){ esame5= esame5+ voti[k][4]; } esame5= esame5/5; printf("%.2f \n", esame5); printf("\n"); for(int k=0; k<5; k++){ studente1=studente1+ voti[0][k]; } studente1= studente1/5; printf("%.2f \n",studente1); for(int k=0; k<5; k++){ studente2= studente2+ voti[1][k]; } studente2= studente2/5; printf("%.2f \n", studente2); for(int k=0; k<5; k++){ studente3= studente3+ voti[2][k]; } studente3= studente3/5; printf("%.2f \n", studente3); for(int k=0; k<5; k++){ studente4= studente4 + voti[3][k]; } studente4= studente4/5; printf("%.2f \n", studente4); for(int k=0; k<5; k++){ studente5= studente5+ voti[4][k]; } studente5= studente5/5; printf("%.2f \n", studente5); }
C
#include <stdlib.h> #include <stdio.h> int main(int argc, char** argv){ if((argc-1) %2 != 0){ printf("Should enter even number of argument\n"); } float vector = 0; int i; for(i = 1; i<=argc/2; i++){ float v1 = atof(argv[i]); float v2 = atof(argv[argc/2+ i]); vector = vector + (v1*v2); } printf("Producto punto is = %.2f\n", vector); return 0; }
C
#include <stdio.h> int main() { int n, b, i, m,counter = 0; printf("Enter the number upto which do you want to print prime numbers \n"); scanf_s("%d", &m); for (b = 2;b <= m;b++){ i = 2; while (b % i != 0){ i++; } if (i == b) { counter++; } } printf("The number of prime numbers less than or equal %d is %d\n", m, counter); return 0; }
C
#include <iostream> #include <errno.h> #include <wiringPiSPI.h> #include <unistd.h> using namespace std; // channel is the wiringPi name for the chip select (or chip enable) pin. // Set this to 0 or 1, depending on how it's connected. static const int CHANNEL = 1; int main() { int fd, result; unsigned char buffer[100]; cout << "Initializing" << endl ; // Configure the interface. // CHANNEL indicates chip select, // 500000 indicates bus speed. fd = wiringPiSPISetup(CHANNEL, 500000); cout << "Init result: " << fd << endl; // clear display buffer[0] = 0x76; wiringPiSPIDataRW(CHANNEL, buffer, 1); sleep(5); // Do a one-hot bit selection for each field of the display // It displays gibberish, but tells us that we're correctly addressing all // of the segments. for(int i = 1; i <= 0x7f; i <<= 1) { // the decimals, colon and apostrophe dots buffer[0] = 0x77; buffer[1] = i; result = wiringPiSPIDataRW(CHANNEL, buffer, 2); // The first character buffer[0] = 0x7b; buffer[1] = i; result = wiringPiSPIDataRW(CHANNEL, buffer, 2); // The second character buffer[0] = 0x7c; buffer[1] = i; result = wiringPiSPIDataRW(CHANNEL, buffer, 2); // The third character buffer[0] = 0x7d; buffer[1] = i; result = wiringPiSPIDataRW(CHANNEL, buffer, 2); // The last character buffer[0] = 0x7e; buffer[1] = i; result = wiringPiSPIDataRW(CHANNEL, buffer, 2); // Pause so we can see them sleep(5); } // clear display again buffer[0] = 0x76; wiringPiSPIDataRW(CHANNEL, buffer, 1); }
C
#include <stdio.h> #include <string.h> #define MAXN 100 char* replaceAll(int* source, int* subStr, int repStr){ int subL= strlen(subStr); int repL= strlen(repStr); char temp[100]; char* ptr= strstr(source, subStr); int i; while (ptr!=NULL){ strcpy(ptr, ptr+subL); if(repL>0){ strcpy(temp, ptr); strcpy(ptr+repL, temp); for(i=0; i<repL; i++) *(ptr+i)= repStr[i]; } ptr=strstr(source, subStr); } return source; } int main() { int n=MAXN; char s[n], subStr[n], repStr[n]; char sub, rep; printf("Input string: "); gets(s); printf("Input word of sub: "); scanf("%c", sub); printf("Input word of rep: "); scanf("%c", rep); replaceAll(s, subStr, repStr); return 0; }
C
#include <stdio.h> /* * 「配列」のポインタを確認してみる */ int main() { int i[10]; int* pi = i; char c[10]; char* pc = c; // ポインタ位置の確認 printf("&i[0]:\t%08x\n", &i[0]); printf("i:\t%08x\n", i); printf("&i[1]:\t%08x\n", &i[1]); printf("++pi:\t%08x\n", ++pi); printf("&i[2]:\t%08x\n", &i[2]); printf("++pi:\t%08x\n", ++pi); printf("\n"); printf("&c[0]:\t%08x\n", &c[0]); printf("c:\t%08x\n", c); printf("&c[1]:\t%08x\n", &c[1]); printf("++pc:\t%08x\n", ++pc); printf("&c[2]:\t%08x\n", &c[2]); printf("++pc:\t%08x\n", ++pc); printf("\n"); // /* char* s = "abcdefg"; while(*s != '\0') { printf("%c\n", *s); s ++; } */ // return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <check.h> #include "../src/arrayheap.h" heap heap_test; int int_compare(void *num1, void *num2) { return *((int *) num1) - *((int *) num2); } void setup (void) { heap_test = arrayheap_methods.create(&int_compare); } void teardown(void) { arrayheap_methods.free(heap_test); } START_TEST (test_heap_create) { fail_if(!heap_test, "heap_create failed."); fail_unless(arrayheap_methods.size(heap_test) == 0, "Size not set correctly on creation"); fail_unless(arrayheap_methods.is_empty(heap_test), "Error: list is not empty"); } END_TEST START_TEST (test_heap_add1) { int error; int *item; int *nums[3]; for (int i = 0; i < 3; i++) { nums[i] = malloc(sizeof(int)); *nums[i] = i; } heap hp = NULL; error = arrayheap_methods.add(hp, nums[0]); fail_unless(error == ERROR_HEAP_IS_NULL, "Error adding to NULL heap"); fail_unless(arrayheap_methods.size(hp) == ERROR_HEAP_IS_NULL, "Size incorrect after adding to NULL heap"); hp = arrayheap_methods.create(&int_compare); fail_if(!hp, "arrayheap_methods.create failed."); for (int i = 0; i < 3; i++) { error = arrayheap_methods.add(hp, nums[i]); fail_unless(error == SUCCESS_HEAP, "Error adding to heap"); fail_unless(arrayheap_methods.size(hp) == (i+1), "Size incorrect after add"); item = (int *) arrayheap_methods.peek(hp); fail_unless(*item == 0, "Error in peek"); fail_unless(arrayheap_methods.contains(hp, nums[i]), "Error in arrayheap_methods.contains"); } for (int i = 0; i < 3; i++) free(nums[i]); arrayheap_methods.free(hp); } END_TEST START_TEST (test_heap_add2) { int error; int *item; int *nums[3]; for (int i = 0; i < 3; i++) { nums[i] = malloc(sizeof(int)); *nums[i] = 2 - i; } heap hp = NULL; error = arrayheap_methods.add(hp, nums[0]); fail_unless(error == ERROR_HEAP_IS_NULL, "Error adding to NULL heap"); fail_unless(arrayheap_methods.size(hp) == ERROR_HEAP_IS_NULL, "Size incorrect after adding to NULL heap"); hp = arrayheap_methods.create(&int_compare); fail_if(!hp, "arrayheap_methods.create failed."); for (int i = 0; i < 3; i++) { error = arrayheap_methods.add(hp, nums[i]); fail_unless(error == SUCCESS_HEAP, "Error adding to heap"); fail_unless(arrayheap_methods.size(hp) == (i+1), "Size incorrect after add"); item = (int *) arrayheap_methods.peek(hp); fail_unless(*item == (2 - i), "Error in peek"); fail_unless(arrayheap_methods.contains(hp, nums[i]), "Error in arrayheap_methods.contains"); } arrayheap_methods.free_items(hp,NULL); } END_TEST START_TEST (test_heap_add3) { int error; int *item; int *nums[8]; for (int i = 0; i < 8; i++) { nums[i] = malloc(sizeof(int)); *nums[i] = 7 - i; } heap hp = NULL; error = arrayheap_methods.add(hp, nums[0]); fail_unless(error == ERROR_HEAP_IS_NULL, "Error adding to NULL heap"); fail_unless(arrayheap_methods.size(hp) == ERROR_HEAP_IS_NULL, "Size incorrect after adding to NULL heap"); hp = arrayheap_methods.create(&int_compare); fail_if(!hp, "arrayheap_methods.create failed."); for (int i = 0; i < 8; i++) { error = arrayheap_methods.add(hp, nums[i]); fail_unless(error == SUCCESS_HEAP, "Error adding to heap"); fail_unless(arrayheap_methods.size(hp) == (i+1), "Size incorrect after add"); item = (int *) arrayheap_methods.peek(hp); fail_unless(*item == (7 - i), "Error in peek"); fail_unless(arrayheap_methods.contains(hp, nums[i]), "Error in arrayheap_methods.contains"); } for (int i = 0; i < 8; i++) free(nums[i]); arrayheap_methods.free(hp); } END_TEST START_TEST (test_heap_to_array) { int error; int *item; int *nums[3]; for (int i = 0; i < 3; i++) { nums[i] = malloc(sizeof(int)); *nums[i] = i; } heap hp = NULL; error = arrayheap_methods.add(hp, nums[0]); fail_unless(error == ERROR_HEAP_IS_NULL, "Error adding to NULL heap"); fail_unless(arrayheap_methods.size(hp) == ERROR_HEAP_IS_NULL, "Size incorrect after adding to NULL heap"); hp = arrayheap_methods.create(&int_compare); fail_if(!hp, "arrayheap_methods.create failed."); for (int i = 0; i < 3; i++) { error = arrayheap_methods.add(hp, nums[i]); fail_unless(error == SUCCESS_HEAP, "Error adding to heap"); fail_unless(arrayheap_methods.size(hp) == (i+1), "Size incorrect after add"); item = (int *) arrayheap_methods.peek(hp); fail_unless(*item == 0, "Error in peek"); fail_unless(arrayheap_methods.contains(hp, nums[i]), "Error in arrayheap_methods.contains"); } int **items = (int **) arrayheap_methods.to_array(hp); for (int i = 0; i < 3; i++) { int found = 0; for (int j = 0; j < 3; j++) { if (i == *items[j]) found = 1; } fail_unless(found == 1, "Error in to_array"); } for (int i = 0; i < 3; i++) free(nums[i]); arrayheap_methods.free(hp); } END_TEST START_TEST (test_heap_remove1) { int error; int *item; int *nums[3]; for (int i = 0; i < 3; i++) { nums[i] = malloc(sizeof(int)); *nums[i] = i; } heap hp = NULL; error = arrayheap_methods.add(hp, nums[0]); fail_unless(error == ERROR_HEAP_IS_NULL, "Error adding to NULL heap"); fail_unless(arrayheap_methods.size(hp) == ERROR_HEAP_IS_NULL, "Size incorrect after adding to NULL heap"); hp = arrayheap_methods.create(&int_compare); fail_if(!hp, "arrayheap_methods.create failed."); for (int i = 0; i < 3; i++) { error = arrayheap_methods.add(hp, nums[i]); fail_unless(error == SUCCESS_HEAP, "Error adding to heap"); fail_unless(arrayheap_methods.size(hp) == (i+1), "Size incorrect after add"); item = (int *) arrayheap_methods.peek(hp); fail_unless(*item == 0, "Error in peek"); fail_unless(arrayheap_methods.contains(hp, nums[i]), "Error in arrayheap_methods.contains"); } for (int i = 0; i < 3; i++) { item = (int *) arrayheap_methods.remove(hp); fail_unless(*item == i, "Error in remove"); fail_unless(arrayheap_methods.size(hp) == 2 - i, "Size incorrect after remove"); } for (int i = 0; i < 3; i++) free(nums[i]); arrayheap_methods.free(hp); } END_TEST START_TEST (test_heap_remove2) { int error; int *item; int *nums[3]; for (int i = 0; i < 3; i++) { nums[i] = malloc(sizeof(int)); *nums[i] = 2 - i; } heap hp = NULL; error = arrayheap_methods.add(hp, nums[0]); fail_unless(error == ERROR_HEAP_IS_NULL, "Error adding to NULL heap"); fail_unless(arrayheap_methods.size(hp) == ERROR_HEAP_IS_NULL, "Size incorrect after adding to NULL heap"); hp = arrayheap_methods.create(&int_compare); fail_if(!hp, "arrayheap_methods.create failed."); for (int i = 0; i < 3; i++) { error = arrayheap_methods.add(hp, nums[i]); fail_unless(error == SUCCESS_HEAP, "Error adding to heap"); fail_unless(arrayheap_methods.size(hp) == (i+1), "Size incorrect after add"); item = (int *) arrayheap_methods.peek(hp); fail_unless(*item == (2 - i), "Error in peek"); fail_unless(arrayheap_methods.contains(hp, nums[i]), "Error in arrayheap_methods.contains"); } for (int i = 0; i < 3; i++) { item = (int *) arrayheap_methods.remove(hp); fail_unless(*item == i, "Error in remove"); fail_unless(arrayheap_methods.size(hp) == 2 - i, "Size incorrect after remove"); } arrayheap_methods.free_items(hp, NULL); } END_TEST START_TEST (test_heap_remove3) { int error; int *item; int *nums[8]; for (int i = 0; i < 8; i++) { nums[i] = malloc(sizeof(int)); *nums[i] = 7 - i; } heap hp = NULL; error = arrayheap_methods.add(hp, nums[0]); fail_unless(error == ERROR_HEAP_IS_NULL, "Error adding to NULL heap"); fail_unless(arrayheap_methods.size(hp) == ERROR_HEAP_IS_NULL, "Size incorrect after adding to NULL heap"); hp = arrayheap_methods.create(&int_compare); fail_if(!hp, "arrayheap_methods.create failed."); for (int i = 0; i < 8; i++) { error = arrayheap_methods.add(hp, nums[i]); fail_unless(error == SUCCESS_HEAP, "Error adding to heap"); fail_unless(arrayheap_methods.size(hp) == (i+1), "Size incorrect after add"); item = (int *) arrayheap_methods.peek(hp); fail_unless(*item == (7 - i), "Error in peek"); fail_unless(arrayheap_methods.contains(hp, nums[i]), "Error in arrayheap_methods.contains"); } for (int i = 0; i < 8; i++) { item = (int *) arrayheap_methods.remove(hp); fail_unless(*item == i, "Error in remove"); fail_unless(arrayheap_methods.size(hp) == 7 - i, "Size incorrect after remove"); } for (int i = 0; i < 8; i++) free(nums[i]); arrayheap_methods.free(hp); } END_TEST START_TEST (test_heap_merge) { int error; int *item; int *nums[8]; for (int i = 0; i < 8; i++) { nums[i] = malloc(sizeof(int)); *nums[i] = 7 - i; } heap hp = NULL; error = arrayheap_methods.add(hp, nums[0]); fail_unless(error == ERROR_HEAP_IS_NULL, "Error adding to NULL heap"); fail_unless(arrayheap_methods.size(hp) == ERROR_HEAP_IS_NULL, "Size incorrect after adding to NULL heap"); hp = arrayheap_methods.create(&int_compare); fail_if(!hp, "arrayheap_methods.create failed."); for (int i = 0; i < 8; i++) { error = arrayheap_methods.add(hp, nums[i]); fail_unless(error == SUCCESS_HEAP, "Error adding to heap"); fail_unless(arrayheap_methods.size(hp) == (i+1), "Size incorrect after add"); item = (int *) arrayheap_methods.peek(hp); fail_unless(*item == (7 - i), "Error in peek"); fail_unless(arrayheap_methods.contains(hp, nums[i]), "Error in arrayheap_methods.contains"); } int *nums2[5]; for (int i = 8; i < 13; i++) { nums2[i-8] = malloc(sizeof(int)); *nums2[i-8] = i; } heap hp2 = NULL; error = arrayheap_methods.add(hp2, nums2[0]); fail_unless(error == ERROR_HEAP_IS_NULL, "Error adding to NULL heap"); fail_unless(arrayheap_methods.size(hp2) == ERROR_HEAP_IS_NULL, "Size incorrect after adding to NULL heap"); hp2 = arrayheap_methods.create(&int_compare); fail_if(!hp2, "arrayheap_methods.create failed."); for (int i = 0; i < 5; i++) { error = arrayheap_methods.add(hp2, nums2[i]); fail_unless(error == SUCCESS_HEAP, "Error adding to heap"); fail_unless(arrayheap_methods.size(hp2) == (i+1), "Size incorrect after add"); item = (int *) arrayheap_methods.peek(hp2); fail_unless(*item == 8, "Error in peek"); fail_unless(arrayheap_methods.contains(hp2, nums2[i]), "Error in arrayheap_methods.contains"); } heap hp3 = arrayheap_methods.merge(hp, hp2); fail_if(hp3 == NULL, "Error in merge"); for (int i = 0; i < 12; i++) { item = (int *) arrayheap_methods.remove(hp3); fail_unless(*item == i, "Error in remove"); fail_unless(arrayheap_methods.size(hp3) == (12 - i), "Size incorrect after remove"); } for (int i = 0; i < 8; i++) free(nums[i]); arrayheap_methods.free(hp); for (int i = 0; i < 5; i++) free(nums2[i]); arrayheap_methods.free(hp2); arrayheap_methods.free(hp3); } END_TEST Suite *heap_suite(void) { Suite *s = suite_create("ArrayList Heap"); /* test constructors and destructors */ TCase *tc_init = tcase_create("Intialize"); tcase_add_checked_fixture(tc_init, setup, teardown); tcase_add_test(tc_init, test_heap_create); suite_add_tcase(s, tc_init); /* test add */ TCase *tc_add = tcase_create("Heap Add"); tcase_add_test(tc_add, test_heap_add1); tcase_add_test(tc_add, test_heap_add2); tcase_add_test(tc_add, test_heap_add3); suite_add_tcase(s, tc_add); /* test remove */ TCase *tc_remove = tcase_create("Heap Remove"); tcase_add_test(tc_remove, test_heap_remove1); tcase_add_test(tc_remove, test_heap_remove2); tcase_add_test(tc_remove, test_heap_remove3); suite_add_tcase(s, tc_remove); /* test to array and merge */ TCase *tc_misc = tcase_create("Heap Array & Merge"); tcase_add_test(tc_misc, test_heap_to_array); tcase_add_test(tc_misc, test_heap_merge); suite_add_tcase(s, tc_misc); return s; } int main(void) { int number_failed; Suite *s = heap_suite(); SRunner *sr = srunner_create(s); srunner_run_all(sr, CK_VERBOSE); number_failed = srunner_ntests_failed(sr); srunner_free(sr); return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; }
C
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <termios.h> #include <time.h> #include <pthread.h> #include <signal.h> #include <string.h> #include "graphic.h" #include "control.h" #include "timer.h" #include "tetris.h" static void sigint(int); static void quit(void); static void draw(void); static void draw_playgrd(void); static void draw_preview(void); static void draw_linerecord(void); static void draw_blockrecord(void); static void draw_status(void); static void draw_block(int preview, int n); static void draw_cur(void); static void* trd_draw(void*); static void* trd_timer(void*); struct termios org; int main() { struct sigaction sa; memset(&sa, 0, sizeof(struct sigaction)); sa.sa_handler = sigint; sigaction(SIGINT, &sa, NULL); atexit(quit); prepare_input(&org); erase_display(); srand(time(NULL)); game_init(); draw(); pthread_mutex_init(&mut, NULL); pthread_cond_init(&cond, NULL); pthread_t tid; pthread_create(&tid, NULL, trd_timer, NULL); pthread_detach(tid); pthread_create(&tid, NULL, trd_draw, NULL); pthread_detach(tid); int c; while(EOF != (c=getchar())) { if(c == 'j') { move_down(); } else if(c == 'k') { rotate(); } else if(c == 'h') { move_left(); } else if(c == 'l') { move_right(); } else if(c == 32) { drop_down(); } else if(c == 'q') { quit(); } else { continue; } } return 0; } static void quit(void) { restore(); restore_input(&org); erase_display(); pthread_mutex_destroy(&mut); pthread_cond_destroy(&cond); printf("\n"); exit(0); } static void draw(void) { center(); draw_playgrd(); draw_preview(); draw_linerecord(); draw_blockrecord(); draw_status(); draw_cur(); fflush(stdout); } static void draw_pad(int bc, int n) { setcolor(0, bc); for(; n>0; --n) printf(" "); restore(); } static void draw_block(int preview, int n) { static const int bc[] = {B_BLACK, B_BLACK, B_RED, B_GREEN, B_YELLOW, B_BLUE, B_MAGENTA, B_CYAN, B_WHITE}; static const char* s[] = {" ", " ", "()", "##", "$$", "{}", "<>", "&&", "[]"}; int f = n==Z ? F_YELLOW : F_WHITE; int b = bc[n]; if(1 == preview) { b = n==EMPTY ? B_BLUE : B_BLACK; f = n==EMPTY ? F_BLUE : F_BLACK;; } setcolor(f, b); printf("%s", s[n]); restore(); } static void draw_preview(void) { int l,c; for(l=0; l<4; ++l) { cursor_to(PRV_LEFT, PRV_TOP+l); draw_pad(B_BLUE, 1); for(c=0; c<4; ++c) { cursor_to(PRV_LEFT+c*2+1, PRV_TOP+l); draw_block(1, GAME->nextgrd[l][c]); } draw_pad(B_BLUE, 1); } cursor_to(PRV_LEFT, PRV_TOP+4); draw_pad(B_BLUE, 10); } static void draw_playgrd(void) { int l,c; for(l=0; l<LINES; ++l) { for(c=0; c<COLS; ++c) { cursor_to(PGRD_LEFT+c*2, PGRD_TOP+l); draw_block(0, GAME->playgrd[l][c]); } } } static void draw_cur(void) { int i; for(i=0; i<4; ++i) { if(GAME->cur[i].line < 0) continue; cursor_to(PGRD_LEFT+GAME->cur[i].col*2, PGRD_TOP+GAME->cur[i].line); draw_block(0, GAME->curtype); } } static void draw_linerecord(void) { cursor_to(LR_LEFT, LR_TOP); setcolor(F_WHITE, B_BLACK); setattr(T_BOLD); printf(" LINE "); restore(); setcolor(F_BLACK, B_WHITE); cursor_to(LR_LEFT, LR_TOP+1); printf(" 1> %5d ", GAME->one); cursor_to(LR_LEFT, LR_TOP+2); printf(" 2> %5d ", GAME->two); cursor_to(LR_LEFT, LR_TOP+3); printf(" 3> %5d ", GAME->three); cursor_to(LR_LEFT, LR_TOP+4); printf(" 4> %5d ", GAME->four); cursor_to(LR_LEFT, LR_TOP+5); setattr(T_UNDERSCORE); printf(" sum %4d ", GAME->one+GAME->two+GAME->three+GAME->four); restore(); } static void draw_blockrecord(void) { cursor_to(BR_LEFT, BR_TOP); setcolor(F_WHITE, B_BLACK); setattr(T_BOLD); printf(" BLOCKS "); restore(); cursor_to(BR_LEFT, BR_TOP+1); setcolor(F_WHITE, B_RED); printf(" (I) %4d ", GAME->i); cursor_to(BR_LEFT, BR_TOP+2); setcolor(F_WHITE, B_GREEN); printf(" #J# %4d ", GAME->j); cursor_to(BR_LEFT, BR_TOP+3); setcolor(F_WHITE, B_YELLOW); printf(" $L$ %4d ", GAME->l); cursor_to(BR_LEFT, BR_TOP+4); setcolor(F_WHITE, B_BLUE); printf(" {O} %4d ", GAME->o); cursor_to(BR_LEFT, BR_TOP+5); setcolor(F_WHITE, B_MAGENTA); printf(" <S> %4d ", GAME->s); cursor_to(BR_LEFT, BR_TOP+6); setcolor(F_WHITE, B_CYAN); printf(" &T& %4d ", GAME->t); cursor_to(BR_LEFT, BR_TOP+7); setcolor(F_YELLOW, B_WHITE); printf(" [Z] %4d ", GAME->z); cursor_to(BR_LEFT, BR_TOP+8); setcolor(F_WHITE, B_BLACK); setattr(T_UNDERSCORE); printf(" sum %4d ", GAME->i+GAME->j+GAME->l+GAME->o+GAME->s+GAME->t+GAME->z); restore(); } static void draw_status(void) { cursor_to(ST_LEFT, ST_TOP); setcolor(F_WHITE, B_BLACK); setattr(T_BOLD); printf(" LEVEL "); restore(); setcolor(F_BLACK, B_WHITE); cursor_to(ST_LEFT, ST_TOP+1); printf("%8d ", GAME->level+1); cursor_to(ST_LEFT, ST_TOP+3); setcolor(F_WHITE, B_BLACK); setattr(T_BOLD); printf(" SCORE "); restore(); setcolor(F_BLACK, B_WHITE); cursor_to(ST_LEFT, ST_TOP+4); printf("%8d ", GAME->score); cursor_to(ST_LEFT, ST_TOP+6); setcolor(F_WHITE, B_BLACK); setattr(T_BOLD); printf(" SPEED "); restore(); setcolor(F_BLACK, B_WHITE); cursor_to(ST_LEFT, ST_TOP+7); printf(" %7.2f ", 1000.0f/speeds[GAME->level]); cursor_to(ST_LEFT, ST_TOP+9); setcolor(F_WHITE, B_BLACK); setattr(T_BOLD); printf("NEXTLEVEL"); restore(); setcolor(F_BLACK, B_WHITE); cursor_to(ST_LEFT, ST_TOP+10); printf("%8d ", levels[GAME->level]-GAME->score); restore(); } static void* trd_draw(void* p) { for(;;) { if(0 == pthread_mutex_lock(&mut)) { pthread_cond_wait(&cond, &mut); draw(); pthread_mutex_unlock(&mut); } } } static void* trd_timer(void* p) { timer_init(); for(;;) { timer_update(); if(timer_interval() >= speeds[GAME->level]) { move_down(); timer_reset(); } usleep(50); } } static void sigint(int n) { quit(); exit(0); }
C
/** 获取网卡down/up/running 状态 */ #include <net/if.h> /* for ifconf */ #include <linux/sockios.h> /* for net status mask */ #include <netinet/in.h> /* for sockaddr_in */ #include <sys/socket.h> #include <sys/types.h> #include <sys/ioctl.h> #include <stdio.h> #define MAX_INTERFACE (4) void port_status(unsigned int flags); /* set == 0: do clean , set == 1: do set! */ int set_if_flags(char *pif_name, int sock, int status, int set) { struct ifreq ifr; int ret = 0; strncpy(ifr.ifr_name, pif_name, strlen(pif_name) + 1); ret = ioctl(sock, SIOCGIFFLAGS, &ifr); if(ret) return -1; /* set or clean */ if(set) ifr.ifr_flags |= status; else ifr.ifr_flags &= ~status; /* set flags */ ret = ioctl(sock, SIOCSIFFLAGS, &ifr); if(ret) return -1; return 0; } int get_if_info(int fd) { struct ifreq buf[MAX_INTERFACE]; struct ifconf ifc; int ret = 0; int if_num = 0; ifc.ifc_len = sizeof(buf); ifc.ifc_buf = (caddr_t) buf; ret = ioctl(fd, SIOCGIFCONF, (char*)&ifc); if(ret) { printf("get if config info failed"); return -1; } /* 网口总数 ifc.ifc_len 应该是一个出入参数 */ if_num = ifc.ifc_len/sizeof(struct ifreq); printf("interface num is interface = %d\n", if_num); while(if_num-- > 0) { printf("net device: %s\n", buf[if_num].ifr_name); /* 获取第n个网口信息 */ ret = ioctl(fd, SIOCGIFFLAGS, (char*)&buf[if_num]); if(ret) continue; /* 获取网口状态 */ port_status(buf[if_num].ifr_flags); /* 获取当前网卡的ip地址 */ ret = ioctl(fd, SIOCGIFADDR, (char*)&buf[if_num]); if(ret) continue; printf("IP address is: \n%s\n", inet_ntoa(((struct sockaddr_in *)(&buf[if_num].ifr_addr))->sin_addr)); /* 获取当前网卡的mac */ ret = ioctl(fd, SIOCGIFHWADDR, (char*)&buf[if_num]); if(ret) continue; printf("%02x:%02x:%02x:%02x:%02x:%02x\n\n", (unsigned char)buf[if_num].ifr_hwaddr.sa_data[0], (unsigned char)buf[if_num].ifr_hwaddr.sa_data[1], (unsigned char)buf[if_num].ifr_hwaddr.sa_data[2], (unsigned char)buf[if_num].ifr_hwaddr.sa_data[3], (unsigned char)buf[if_num].ifr_hwaddr.sa_data[4], (unsigned char)buf[if_num].ifr_hwaddr.sa_data[5] ); } } void port_status(unsigned int flags) { if(flags & IFF_UP) { printf("is up\n"); } if(flags & IFF_BROADCAST) { printf("is broadcast\n"); } if(flags & IFF_LOOPBACK) { printf("is loop back\n"); } if(flags & IFF_POINTOPOINT) { printf("is point to point\n"); } if(flags & IFF_RUNNING) { printf("is running\n"); } if(flags & IFF_PROMISC) { printf("is promisc\n"); } } int main() { int fd; fd = socket(AF_INET, SOCK_DGRAM, 0); if(fd > 0) { get_if_info(fd); close(fd); } return 0; }
C
#import <stdio.h> #import <cs50.h> /*The following promts the user for a credit card number and determines if a entered value is a valid AMEX, VISA or MASTERCARD credit card number. If the entered card number is valid the card type will print. If the number entered is not a valid credit card number "INVALID" will print to the console. */ int main(void) { long numOne; long numOne2 = 0; long numTwo; long numTwo2 = 0; long numThree; long numThree2 = 0; long numFour; long numFour2 = 0; long numFive; long numFive2 = 0; long numSix; long numSix2 = 0; long numSeven; long numSeven2 = 0; long numEight; long numEight2 = 0; long number = get_long("Number: "); /*The following assigns a variable (num...)to each of the digits making up a credit card number starting with second to last number and doulbes it. This opperation is perfomed from right to left. If the product is comprised of two digits (i.e. 6 * 2 = 12) it assigns a variable (num...2) to each digit (i.e '1' and '2'). */ { numOne = (((number % 100) - (number % 10)) / 10) * 2; if (numOne > 9) { numOne2 = numOne % 10; numOne = numOne - (numOne % 10) - 9; } numTwo = (((number % 10000) - (number % 1000)) / 1000) * 2; if (numTwo > 9) { numTwo2 = numTwo % 10; numTwo = numTwo - (numTwo % 10) - 9; } numThree = (((number % 1000000) - (number % 100000)) / 100000) * 2; if (numThree > 9) { numThree2 = numThree % 10; numThree = numThree - (numThree % 10) - 9; } numFour = (((number % 100000000) - (number % 10000000)) / 10000000) * 2; if (numFour > 9) { numFour2 = numFour % 10; numFour = numFour - (numFour % 10) - 9; } numFive = (((number % 10000000000) - (number % 1000000000)) / 1000000000) * 2; if (numFive > 9) { numFive2 = numFive % 10; numFive = numFive - (numFive % 10) - 9; } numSix = (((number % 1000000000000) - (number % 100000000000)) / 100000000000) * 2; if (numSix > 9) { numSix2 = numSix % 10; numSix = numSix - (numSix % 10) - 9; } numSeven = (((number % 100000000000000) - (number % 10000000000000)) / 10000000000000) * 2; if (numSeven > 9) { numSeven2 = numSeven % 10; numSeven = numSeven - (numSeven % 10) - 9; } numEight = (((number % 10000000000000000) - (number % 1000000000000000)) / 1000000000000000) * 2; if (numEight > 9) { numEight2 = numEight % 10; numEight = numEight - (numEight % 10) - 9; } //The digits of the products found in the preceeding operation are added together. long sumOne = numOne + numOne2 + numTwo + numTwo2 + numThree + numThree2 + numFour + numFour2 + numFive + numFive2 + numSix + numSix2 + numSeven + numSeven2 + numEight + numEight2; long otherOne; long otherTwo; long otherThree; long otherFour; long otherFive; long otherSix; long otherSeven; long otherEight; //Variables (other...) are assigned to the remaining card numbers. { otherOne = (number % 10); otherTwo = (((number % 1000) - (number % 100)) / 100); otherThree = (((number % 100000) - (number % 10000)) / 10000); otherFour = (((number % 10000000) - (number % 1000000)) / 1000000); otherFive = (((number % 1000000000) - (number % 100000000)) / 100000000); otherSix = (((number % 100000000000) - (number % 10000000000)) / 10000000000); otherSeven = (((number % 10000000000000) - (number % 1000000000000)) / 1000000000000); otherEight = (((number % 1000000000000000) - (number % 100000000000000)) / 100000000000000); //The digits of the products found in the preceeding operation are added together. long sumTwo = otherOne + otherTwo + otherThree + otherFour + otherFive + otherSix + otherSeven + otherEight; long checkSum = sumOne + sumTwo; //Sets logic for VISA cards which are comprised of either 13 or 16 numbers and always begin with a '4'. if (((number > 3999999999999 && number < 5000000000000) && checkSum % 10 == 0) || ((number > 3999999999999999 && number < 4999999999999999) && checkSum % 10 == 0)) { printf("VISA\n"); } //Sets logic for MASTERCARD which is always 16 digits long and starts with a 51,52,52,54 or 55. else if (number > 4999999999999999 && number < 5599999999999999 && checkSum % 10 == 0) { printf("MASTERCARD\n"); } //Sets logic for AMEX which is always 15 digits long and start with either a 34 or 37. else if (((number > 339999999999999 && number < 349999999999999) && checkSum % 10 == 0) || ((number > 369999999999999 && number < 379999999999999) && checkSum % 10 == 0)) { printf("AMEX\n"); } else //If the number does not meet any of the above conditions it is inivalid. { printf("INVALID\n"); } } } }
C
/* * OPERATING SYSTEMS DESING - 16/17 * * @file test.c * @brief Implementation of the client test routines. * @date 01/03/2017 */ #include <stdio.h> #include <string.h> #include "include/filesystem.h" #include <stdlib.h> #include <fcntl.h> // Color definitions for asserts #define ANSI_COLOR_RESET "\x1b[0m" #define ANSI_COLOR_RED "\x1b[31m" #define ANSI_COLOR_GREEN "\x1b[32m" #define ANSI_COLOR_BLUE "\x1b[34m" #define N_BLOCKS 25 // Number of blocks in the device #define DEV_SIZE N_BLOCKS * BLOCK_SIZE // Device size, in bytes #define TEST_PASSED(test_name...) fprintf(stdout, "%s%s%s%s%s%s", ANSI_COLOR_BLUE, "TEST ", test_name, ANSI_COLOR_GREEN, " SUCCESS\n\n", ANSI_COLOR_RESET) #define TEST_FAILED(test_name...) fprintf(stdout, "%s%s%s%s%s%s", ANSI_COLOR_BLUE, "TEST ", test_name, ANSI_COLOR_RED, " FAILED\n\n", ANSI_COLOR_RESET) #define TEST_PRINT(test_number, requirement_tested...) fprintf(stdout, "%s%s%s%s%s", "TEST NUMBER ", test_number, ": REQUIREMENT ", requirement_tested, "\n") int main() { fprintf(stdout, "\nThis test is designed to run on disks that have a minimum size of 3000 blocks, please run \"./create_disk 3000\" before running this test\n\n"); //FUNCTIONAL REQUIREMENTS TESTS fprintf(stdout, "%s", "BASIC TESTING OF FUNCTIONAL REQUIREMENTS\n\n"); /** * @test 1 * @requirement F1.1, F9, NF6 * @description Create a file system. The file system can be created on partitions of the device smaller than * its maximum size. The file system will be used on disks from 50 KiB to 10 MiB. */ TEST_PRINT("1", "F1.1, F9, NF6"); if (mkFS(24 * BLOCK_SIZE) == -1 && mkFS(BLOCK_SIZE * 3000) == 0 && mkFS(5121 * BLOCK_SIZE) == -1) { TEST_PASSED("mkFS"); } else { TEST_FAILED("mkFS"); return -1; } /** * @test 2 * @requirement F1.2 * @description Mount a file system */ TEST_PRINT("2", "F1.2"); if (mountFS() == 0) { TEST_PASSED("mountFS"); } else { TEST_FAILED("mountFS"); } /** * @test 3 * @requirement F1.4 * @description Create a file within the file system */ TEST_PRINT("3", "F1.4"); if (createFile("test.txt") == 0 && createFile("test.txt") == -1) { // NOLINT TEST_PASSED("createFile"); } else { TEST_FAILED("createFile"); } /** * @test 4 * @requirement F1.6 * @description Open an existing file */ TEST_PRINT("4", "F1.6"); int testFileDescriptor = openFile("test.txt"); if (testFileDescriptor == 0 && openFile("random.txt") == -1) { TEST_PASSED("openFile"); } else { TEST_FAILED("openFile"); } // Fill the buffer with text using C standard functions to avoid introducing errors char *write_buffer = "#INIT#Por cuanto por parte de vos, Miguel de Cervantes, nos fue fecha relación que habíades compuesto " "un libro intitulado El ingenioso hidalgo de la Mancha, el cual os había costado mucho trabajo y era muy " "útil y provechoso, nos pedistes y suplicastes os mandásemos dar licencia y facultad para le poder imprimir," " y previlegio por el tiempo que fuésemos servidos, o como la nuestra merced fuese; lo cual visto por los del" " nuestro Consejo, por cuanto en el dicho libro se hicieron las diligencias que la premática últimamente por nos " "fecha sobre la impresión de los libros dispone, fue acordado que debíamos mandar dar esta nuestra cédula para vos," " en la dicha razón; y nos tuvímoslo por bien. Por la cual, por os hacer bien y merced, os damos licencia y facultad " "para que vos, o la persona que vuestro poder hubiere, y no otra alguna, podáis imprimir el dicho libro, intitulado " "El ingenioso hidalgo de la Mancha, que desuso se hace mención, en todos estos nuestros reinos de Castilla, por tiempo" " y espacio de diez años, que corran y se cuenten desde el dicho día de la data desta nuestra cédula; so pena que la " "persona o personas que, sin tener vuestro poder, lo imprimiere o vendiere, o hiciere imprimir o vender, por el mesmo " "caso pierda la impresión que hiciere, con los moldes y aparejos della; y más, incurra en pena de cincuenta mil maravedís " "cada vez que lo contrario hiciere. La cual dicha pena sea la tercia parte para la persona que lo acusare, y la otra tercia " "parte para nuestra Cámara, y la otra tercia parte para el juez que lo sentenciare. Con tanto que todas las veces que " "hubiéredes de hacer imprimir el dicho libro, durante el tiempo de los dichos diez años, le traigáis al nuestro Consejo, " "juntamente con el original que en él fue visto, que va rubricado cada plana y firmado al fin dél de Juan Gallo de Andrada, " "nuestro Escribano de Cámara, de los que en él residen, para saber si la dicha impresión está conforme el original; o " "traigáis fe en pública forma de cómo por corretor nombrado por nuestro mandado, se vio y corrigió la dicha impresión por el " "original, y se imprimió conforme a él, y quedan impresas las erratas por él apuntadas, para cada un libro de los que así " "fueren impresos, para que se tase el precio que por cada volume hubiéredes de haber. Y mandamos al impresor que así imprimiere " "el dicho libro, no imprima el principio ni el primer pliego dél, ni entregue más de un solo libro con el original al autor, o" " persona a cuya costa lo imprimiere, ni otro alguno, para efeto de la dicha correción y tasa, hasta que antes y primero el " "dicho libro esté corregido y tasado por los del nuestro Consejo; y, estando hecho, y no de otra manera, pueda imprimir el dicho " "principio y primer pliego, y sucesivamente ponga esta nuestra cédula y la aprobación, tasa y erratas, so pena de caer e incurrir " "en las penas contenidas en las leyes y premáticas destos nuestros reinos. Y mandamos a los del nuestro Consejo, y a otras " "cualesquier justicias dellos, guarden y cumplan est"; /** * @test 5 * @requirement F1.9, F7 * @description Write to an opened file. A file could be modified by means of write operations. */ TEST_PRINT("5", "F1.9, F7"); if (writeFile(testFileDescriptor, write_buffer, sizeof(write_buffer) - sizeof(char) * 8) == sizeof(write_buffer) - sizeof(char) * 8) { lseekFile(testFileDescriptor, 0, FS_SEEK_BEGIN); if (writeFile(testFileDescriptor, write_buffer, sizeof(char) * 8) == sizeof(char) * 8) { TEST_PASSED("writeFile"); } else { TEST_FAILED("writeFile"); } } else { TEST_FAILED("writeFile"); } lseekFile(testFileDescriptor, 0, FS_SEEK_BEGIN); /** * @test 6 * @requirement F1.8 * @description Read from an opened file */ TEST_PRINT("6", "F1.8"); char read_buffer[sizeof(write_buffer)]; if (readFile(testFileDescriptor, read_buffer, sizeof(char) * 3) == sizeof(char) * 3) { if (readFile(testFileDescriptor, read_buffer, sizeof(write_buffer)) == sizeof(write_buffer) - 3) { if (readFile(testFileDescriptor, read_buffer, sizeof(char)) == 0) { TEST_PASSED("readFile"); } else { TEST_FAILED("readFile"); } } else { TEST_FAILED("readFile"); } } else { TEST_FAILED("readFile"); } /** * @test 7 * @requirement F1.10 * @description Modify the position of the seek pointer */ TEST_PRINT("7", "F1.10"); char read_string[8] = {0}; char *init_string = "#INIT#"; if (lseekFile(testFileDescriptor, 10, FS_SEEK_BEGIN) == 0) { readFile(testFileDescriptor, read_string, sizeof(char) * 6); if (strcmp(read_string, init_string) == 0) { TEST_PASSED("lseekFile"); } else { TEST_FAILED("lseekFile"); } } else { TEST_FAILED("lseekFile"); } /** * @test 8 * @requirement F1.7 * @description Close an opened file */ TEST_PRINT("8", "F1.7"); if (closeFile(testFileDescriptor) == 0) { TEST_PASSED("closeFile"); } else { TEST_FAILED("closeFile"); } // Testing writing on the device unmountFS(); mountFS(); /** * @test 9 * @requirement F2 * @description Every time a file is opened, its seek pointer will be reset to the beginning of the file. */ TEST_PRINT("9", "F2"); testFileDescriptor = openFile("test.txt"); readFile(testFileDescriptor, read_buffer, sizeof(char) * 6); if (strcmp(read_buffer, init_string) == 0) { TEST_PASSED("lseek reset on openFile"); } else { TEST_FAILED("lseek reset on openFile"); } /** * @test 10 * @requirement F1.11 * @description Check the integrity an existing file */ TEST_PRINT("10", "F1.11"); if (checkFile("test.txt") == -2) { closeFile(testFileDescriptor); if (checkFile("test.txt") == 0) { bwrite("disk.dat", 5, write_buffer); if (checkFile("test.txt") == -1) { TEST_PASSED("checkFile"); } else { TEST_FAILED("checkFile"); } } else { TEST_FAILED("checkFile"); } } else { TEST_FAILED("checkFile"); } /** * @test 11 * @requirement F1.5 * @description Remove an existing file from the file system */ TEST_PRINT("11", "F1.5"); if (removeFile("test.txt") == 0 && removeFile("test.txt") == -1) { // NOLINT TEST_PASSED("removeFile"); } else { TEST_FAILED("removeFile"); } /** * @test 12 * @requirement F5 * @description File integrity must be checked, at least, on open operations. */ TEST_PRINT("12", "F5"); createFile("test.txt"); testFileDescriptor = openFile("test.txt"); writeFile(testFileDescriptor, write_buffer, sizeof(char) * 750); closeFile(testFileDescriptor); bwrite("disk.dat", 5, write_buffer); testFileDescriptor = openFile("test.txt"); if (testFileDescriptor == -2) { TEST_PASSED("integrity check on openFile"); } else { TEST_FAILED("integrity check on openFile"); } removeFile("test.txt"); /** * @test 13 * @requirement F6 * @description The whole contents of a file could be read by means of several read operations. */ TEST_PRINT("13", "F6"); createFile("test.txt"); testFileDescriptor = openFile("test.txt"); writeFile(testFileDescriptor, write_buffer, sizeof(write_buffer)); lseekFile(testFileDescriptor, 0, FS_SEEK_BEGIN); int sumBytes = readFile(testFileDescriptor, read_buffer, sizeof(char) * sizeof(write_buffer) / 4); // NOLINT sumBytes += readFile(testFileDescriptor, read_buffer, sizeof(char) * sizeof(write_buffer) / 4); // NOLINT sumBytes += readFile(testFileDescriptor, read_buffer, sizeof(char) * sizeof(write_buffer) / 4); // NOLINT sumBytes += readFile(testFileDescriptor, read_buffer, sizeof(char) * sizeof(write_buffer) / 4); // NOLINT if (sumBytes == sizeof(write_buffer)) { TEST_PASSED("read in several readFiles"); } else { TEST_FAILED("read in several readFiles"); } // Read metadata for test 15 char *metadata_buffer1 = malloc(BLOCK_SIZE); bread("disk.dat", 1, metadata_buffer1); /** * @test 14 * @requirement F8 * @description As part of a write operation, file capacity may be extended by means of additional data blocks. */ TEST_PRINT("14", "F8"); writeFile(testFileDescriptor, write_buffer, sizeof(write_buffer)); lseekFile(testFileDescriptor, 0, FS_SEEK_BEGIN); if (readFile(testFileDescriptor, read_buffer, sizeof(write_buffer) * 2) == sizeof(write_buffer) * 2) { TEST_PASSED("extend file capacity with writeFile"); } else { TEST_FAILED("extend file capacity with writeFile"); } closeFile(testFileDescriptor); removeFile("test.txt"); /** * @test 15 * @requirement F1.3 * @description Unmount a file system */ TEST_PRINT("15", "F1.3"); if (unmountFS() == 0) { TEST_PASSED("unmountFS"); } else { TEST_FAILED("unmountFS"); } //NON-FUNCTIONAL REQUIREMENTS TESTS fprintf(stdout, "%s", "BASIC TESTING OF NON-FUNCTIONAL REQUIREMENTS\n\n"); mountFS(); /** * @test 16 * @requirement NF1 * @description The maximum number of files in the file system will never be higher than 40. */ TEST_PRINT("16", "NF1"); char buffer[12] = {0}; int iteration = 1; sprintf(buffer, "file%d.txt", iteration); while (createFile(buffer) == 0) { iteration++; sprintf(buffer, "file%d.txt", iteration); } if (iteration == 41) { TEST_PASSED("max number of files"); for (iteration = 40; iteration > 0; --iteration) { sprintf(buffer, "file%d.txt", iteration); removeFile(buffer); } } else { TEST_FAILED("max number of files"); } /** * @test 17 * @requirement NF2 * @description The maximum length of the file name will be 32 characters. */ TEST_PRINT("17", "NF2"); if (createFile("thisFilenameIsExactly32Chars.txt") == 0 && createFile("thisFilenameIsMoreThan32Chars.txt") == -2) { TEST_PASSED("file name length"); } else { TEST_FAILED("file name length"); } /** * @test 18 * @requirement NF3 * @description The maximum size of the file will be 1 MiB. */ TEST_PRINT("18", "NF3"); testFileDescriptor = openFile("thisFilenameIsExactly32Chars.txt"); char *superSizedArray = calloc(MAX_FILE_SIZE * 2, sizeof(char)); if (writeFile(testFileDescriptor, superSizedArray, sizeof(char) * MAX_FILE_SIZE * 2) == MAX_FILE_SIZE) { TEST_PASSED("1 MiB max file size"); } else { TEST_FAILED("1 MiB max file size"); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <math.h> extern int pop(); extern void push(int); extern void addHeap(int thing2add); extern int heapSize(); extern int heapDelete(); extern int isEmpty(); extern void preOrder(int x); int main(int argc, char * argv[]) { int value; int i; int size; // read input. while (scanf("%d", &value) != EOF) { fprintf(stderr, "READING INPUT: %d\n", value); addHeap(value); } //print heap in valid xml format(tree structure) preOrder(0); size = heapSize(); //delete items from heap while printing them, parent before child. Push items onto stack. for (i = 0; i<size; i++){ push(heapDelete()); } //pop stack until no items remain. while (isEmpty() == 0){ printf("\n %d",pop()); } exit(0); }
C
#include <stdio.h> #include <stdlib.h> char* lerTexto(char* shell, int tamanho); int lerInteiro(char* shell); void* liberarPonteiro(void* ponteiro); int lerInteiro(char* shell) { int inteiro; printf("%s",shell); scanf("%d", &inteiro); return inteiro; } char* lerTexto(char* shell, int tamanho) { char* texto = (char*) calloc(tamanho, sizeof(char)); printf("%s: ", shell); gets(texto); return texto; } void* liberarPonteiro(void* ponteiro) { if (ponteiro != NULL) { free(ponteiro); ponteiro = NULL; } return NULL; }
C
#include "List.h" #include<stdlib.h> #include<stdio.h> int Factorial(int n) { if(n==1) { return 1; } return n*Factorial(n-1); } List *Permutations(int n) { if(n==1) { List arrary[1]={NULL}; Position p=(Position)malloc(sizeof(struct Node)); p->Element=1; p->next=NULL; arrary[0]=p; return arrary; } List *list=(List *)calloc(Factorial(n),sizeof(struct Node)); int size=0; int length=Factorial(n-1); List *array=Permutations(n-1); for(int i=0;i<length;i++) { List L=array[i]; Position p=L; list[size++]=CopyList(InsertHead(n,L)); for(int i=0;i<n-1;i++) { Insert(n,L,p); list[size++]=CopyList(L); Remove(p,L); p=p->next; } free(L); L=NULL; } return list; }
C
// // Created by zhang on 2017/1/7. // //C 库函数 size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr) //根据 format 中定义的格式化规则,格式化结构 timeptr 表示的时间,并把它存储在 str 中。 //str -- 这是指向目标数组的指针,用来复制产生的 C 字符串。 //maxsize -- 这是被复制到 str 的最大字符数。 //format -- 这是 C 字符串,包含了普通字符和特殊格式说明符的任何组合。 // 这些格式说明符由函数替换为表示 tm 中所指定时间的相对应值。格式说明符是: #include <stdio.h> #include <time.h> int strftime_main () { time_t rawtime; struct tm *info; char buffer[80]; time( &rawtime ); info = localtime( &rawtime ); strftime(buffer,80,"%A %B %Y-%m-%j - %I:%M:%S %p", info); printf("format time :|- %s -|\n", buffer ); } //%a 缩写的星期几名称 Sun //%A 完整的星期几名称 Sunday //%b 缩写的月份名称 Mar //%B 完整的月份名称 March //%c 日期和时间表示法 Sun Aug 19 02:56:02 2012 //%d 一月中的第几天(01-31) 19 //%H 24 小时格式的小时(00-23) 14 //%I 12 小时格式的小时(01-12) 05 //%j 一年中的第几天(001-366) 231 //%m 十进制数表示的月份(01-12) 08 //%M 分(00-59) 55 //%p AM 或 PM 名称 PM //%S 秒(00-61) 02 //%U 一年中的第几周,以第一个星期日作为第一周的第一天(00-53) 33 //%w 十进制数表示的星期几,星期日表示为 0(0-6) 4 //%W 一年中的第几周,以第一个星期一作为第一周的第一天(00-53) 34 //%x 日期表示法 08/19/12 //%X 时间表示法 02:50:06 //%y 年份,最后两个数字(00-99) 01 //%Y 年份 2012 //%Z 时区的名称或缩写 CDT //%% 一个 % 符号 %
C
#include <stdio.h> #include <stdlib.h> typedef int Item; typedef struct Node* Link; struct Node{ Item item; Link next; }; int main(int argc, char** argv){ int a = 77; const size_t INT_SIZE = sizeof(int); int* ptr_a = (int*) malloc(3*INT_SIZE); int* new_ptr_a = ptr_a; ptr_a[0] = a; printf("adress from prtf: %d\n", ptr_a); printf("adress from new_prtf: %d\n", new_ptr_a); printf("a value is: %d\n", a); printf("a value from prt: %d\n", *ptr_a); printf("a value from new_prt: %d\n", *new_ptr_a); printf("\n"); printf("clear ptr\n"); free(ptr_a); printf("clear from prt: %d\n", *ptr_a); printf("clear new_prt: %d\n", *new_ptr_a); printf("\n"); a = 777; new_ptr_a[0] = a; printf("new a value is: %d\n", a); printf("new a value from prt: %d\n", *ptr_a); printf("new a value from new_prt: %d\n", *new_ptr_a); printf("adress from prtf: %d\n", ptr_a); printf("adress from new_prtf: %d\n", new_ptr_a); printf("\n"); printf("overadress: %d\n", ptr_a[10]); printf("overadress: %d\n", ptr_a[3]); // int* new_ptr_a = ptr_a; // // // // printf("a value is: %d\n", a); // printf("a value from prt:%d\n", *new_ptr_a); // // printf("clear new_ptf\n"); // del new_ptr_a; // printf("a value is: %d\n", a); // // // printf("Badass ptr\n"); // printf("a value from prt: %d\n", *ptr_a); // printf("a value from new_prt: %d\n", *new_ptr_a); return 0; }
C
/* 结构体练习 */ #include <stdio.h> typedef struct { int x, y; } pt; typedef struct { pt pt1, pt2; } rect; int main(){ pt pt1 = {1, 2}; rect r = {{3, 7}, {8, 13}}; printf("(%d, %d)\n", pt1.x, pt1.y); printf("(%d, %d) (%d, %d)\n", r.pt1.x, r.pt1.y, r.pt2.x, r.pt2.y); return 0; }
C
#include "pid.h" //ƶ static uint8_t no=0; //޷ int constrain(int source ,int min ,int max) { if(source > max) return max; else if(source < min) return min; else return source; } //ʼPIDƶ void PidInit(pHPID_CTR obj,int expect,float Kp,float Ki,float Kd) { obj->no = no++; //ݳʼ˳ɿϵͳ obj->expect = expect; obj->Argv.Kp = Kp; obj->Argv.Ki = Ki; obj->Argv.Kd = Kd; obj->Data.error_Kp = 0; obj->Data.error_Ki = 0; obj->Data.error_Kd = 0; } //PID int PidControl(pHPID_CTR obj,int input) { //㱾ƫ short error = obj->expect - input; //D obj->Data.error_Kd = error - obj->Data.error_Kp; //P obj->Data.error_Kp = error; //I obj->Data.error_Ki += error; PidControlHeadCallBack(obj); //P obj->feedback.back_Kp = obj->Data.error_Kp * obj->Argv.Kp; //I obj->feedback.back_Ki = obj->Data.error_Ki * obj->Argv.Ki; //D obj->feedback.back_Kd = obj->Data.error_Kd * obj->Argv.Kd; return PidControlCallBack(obj); } //ںPID int PidFuseControl(pHPID_CTR obj,int inputP,int inputD) { obj->Data.error_Kp = obj->expect - inputP; //P obj->Data.error_Ki += obj->Data.error_Kp; //I obj->Data.error_Kd = 0-inputD; //D PidControlHeadCallBack(obj); //P obj->feedback.back_Kp = obj->Data.error_Kp * obj->Argv.Kp; //I obj->feedback.back_Ki = obj->Data.error_Ki * obj->Argv.Ki; //D obj->feedback.back_Kd = obj->Data.error_Kd * obj->Argv.Kd; return PidControlCallBack(obj); } //PID int PidDoubleControl(pHDPID_CTR obj,int Oninput,int Ininput) { //⻷Ϊڻ obj->In.expect = PidControl(&obj->Out,Oninput); //ڻ return PidControl(&obj->In,Ininput); //ڻֵ } //PIDֵд __weak void PidControlHeadCallBack(pHPID_CTR obj) { switch(obj->no) { case 0: { if(obj->Data.error_Kp>(3000+obj->expect)||obj->Data.error_Kp<(-3000+obj->expect)) obj->Data.error_Ki = 0; else obj->Data.error_Ki = constrain(obj->Data.error_Ki,-15000,15000); }break; } } //PIDֵд __weak int PidControlCallBack(pHPID_CTR obj) { return constrain(obj->feedback.back_Kp+obj->feedback.back_Ki+obj->feedback.back_Kd,-7000,7000); }
C
#include "Strand2dFCBlockSolver.h" void Strand2dFCBlockSolver::edgeExtract() { // form local edges in the standard element nElemEdge = meshOrder; elemEdge.allocate(nElemEdge,2); if (meshOrder == 1){ elemEdge(0,0) = 0; elemEdge(0,1) = 1; } else if (meshOrder == 2){ elemEdge(0,0) = 0; elemEdge(0,1) = 2; elemEdge(1,0) = 2; elemEdge(1,1) = 1; } else if (meshOrder == 3){ elemEdge(0,0) = 0; elemEdge(0,1) = 2; elemEdge(1,0) = 2; elemEdge(1,1) = 3; elemEdge(2,0) = 3; elemEdge(2,1) = 1; } else if (meshOrder == 4){ elemEdge(0,0) = 0; elemEdge(0,1) = 2; elemEdge(1,0) = 2; elemEdge(1,1) = 3; elemEdge(2,0) = 3; elemEdge(2,1) = 4; elemEdge(3,0) = 4; elemEdge(3,1) = 1; } /* for (int n=0; n<nElemEdge; n++) cout << n << " " << elemEdge(n,0) << " " << elemEdge(n,1) << endl; exit(0); */ // form global list of edges // edge(n,0) = left node on edge n // edge(n,1) = right node on edge n // edge(n,2) = left limiter extension node on edge n // edge(n,3) = right limiter extension node on edge n nSurfEdge = nSurfElem*meshOrder; surfEdge.allocate(nSurfEdge,4);//NOTE: THIS SHOULD BE IN LOCAL ELEMENTS nSurfEdge = 0; for (int n=0; n<nSurfElem; n++) for (int i=0; i<meshOrder; i++){ surfEdge(nSurfEdge ,0) = surfElem(n,elemEdge(i,0)); surfEdge(nSurfEdge++,1) = surfElem(n,elemEdge(i,1)); } // form edge extension nodes, setting the extension node to the opposite // edge node for edges that impinge on the boundary int n1,n2; Array2D<int> psp(nSurfNode,2); psp.set(-1); for (int n=0; n<nSurfEdge; n++){ n1 = surfEdge(n,0); n2 = surfEdge(n,1); psp(n1,1) = n2; psp(n2,0) = n1; } for (int n=0; n<nSurfEdge; n++){ n1 = surfEdge(n,0); n2 = surfEdge(n,1); if (psp(n1,0) == -1) surfEdge(n,2) = n2; else surfEdge(n,2) = psp(n1,0); if (psp(n2,1) == -1) surfEdge(n,3) = n1; else surfEdge(n,3) = psp(n2,1); } /* for (int n=0; n<nSurfEdge; n++) cout << n << " " << surfEdge(n,2) << " " << surfEdge(n,0) << " " << surfEdge(n,1) << " " << surfEdge(n,3) << " " << endl; */ // determine if boundary nodes are on the right or left side of the domain bndSign.allocate(nBndNode); bndElem.allocate(nBndNode,2); Array1D<int> flag(nSurfNode); flag.set(-1); for (int n=0; n<nBndNode; n++) flag(bndNode(n)) = n; for (int n=0; n<nSurfElem; n++){ n1 = flag(surfElem(n,0)); n2 = flag(surfElem(n,1)); if (n1 > -1) bndSign(n1) = -1.; //left boundary if (n2 > -1) bndSign(n2) = 1.; //right boundary for (int i=0; i<meshOrder+1; i++){ n1 = flag(surfElem(n,i)); if (n1 > -1){ bndElem(n1,0) = n; bndElem(n1,1) = i; } }} //for (int n=0; n<nBndNode; n++) //cout << bndNode(n) << " " << bndSign(n) << endl; // clean up psp.deallocate(); flag.deallocate(); }
C
#include <stdio.h> // 헤더 파일 선언 int main() { // main 함수의 시작 printf("Hello"); // 문자열의 출력 return 0; // 0의 반환 } // 함수의 끝
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char* argv[]) { int numbrix[100][100]; int height = 1, width = 1; int i, j; int n, m; int heit = 0; int wid = 1; //real width char z; FILE* file = fopen(argv[1], "r"); if (file == 0) { printf("Could not open file\n"); } char temp[300]; while (fgets(temp, sizeof(temp), file)) { // count hcnt -> height heit++; } fseek(file, 0, SEEK_SET); z = getc(file); for (j = 1; j <= heit; j++) { width = 1; for (i = 1; ; i++) { if (z == 32) z = getc(file); else if (z >= 48 && z <= 57) { // 1 <= z <= 9일경우에 (assert (ayx = z)) //////////////////////////: n = z - '0'; z = getc(file); if (z >= 48 && z <= 57) { // 또 숫자면 십의 자리 숫자인 것이다. m = z - '0'; numbrix[height][width] = n * 10 + m; printf("%2d ", numbrix[height][width]); z = getc(file); width++; } else if (z == 32) { // " "인 경우이다. numbrix[height][width] = n; z = getc(file); printf("%2d ", numbrix[height][width]); width++; } } else if (z == '?') { // 받은 문자가 "?"일 경우 "0"를 넣기. numbrix[height][width] = 0; printf("%2d ", numbrix[height][width]); width++; z = getc(file); } else if (z == '\n') { // 받은 문자가 "\n"일 경우에 height 높이고 다음문자로 넘어가기. height++; z = getc(file); wid = width - 1; printf("\n"); break; } } wid = width - 1; } fclose(file); // x= wid; // y= heit FILE* fp = fopen("formula", "w"); int x, y; // declare-const for (y = 1; y <= heit; y++) for (x = 1; x <= wid; x++) fprintf(fp, "(declare-const a%d%d Int)\n", y, x); for (y = 1; y <= heit; y++) { for (x = 1; x <= wid; x++) { if (numbrix[y][x] != 0) fprintf(fp, "(assert (= a%d%d %d))\n", y, x, numbrix[y][x]); } } // value scope is 0 < n <= 36 for (y = 1; y <= heit; y++) for (x = 1; x <= wid; x++) fprintf(fp, "(assert (and (< 0 a%d%d) (<= a%d%d %d)))\n", y, x, y, x, heit * wid); // 서로 다른 값이어야 한다. fprintf(fp, "(assert (distinct"); for (y = 1; y <= heit; y++) for (x = 1; x <= wid; x++) fprintf(fp, " a%d%d", y, x); fprintf(fp, "))\n"); //수정한부분 (1, 36 이외에 -> 해결_중앙, x축, y축) _ 검사받기 //주위에 n-1이 있다. // n값이 1, 36이 아닐 경우 주위에 n-1 혹은 n+1이 반드시 있다. for (y = 2; y <= heit - 1; y++) { for (x = 2; x <= wid - 1; x++) { fprintf(fp, "(assert (and (or"); fprintf(fp, " (= (- a%d%d 1) a%d%d)", y, x, y - 1, x); fprintf(fp, " (= (- a%d%d 1) a%d%d)", y, x, y + 1, x); fprintf(fp, " (= (- a%d%d 1) a%d%d)", y, x, y, x - 1); fprintf(fp, " (= (- a%d%d 1) a%d%d)", y, x, y, x + 1); fprintf(fp, ") (or"); fprintf(fp, " (= (+ a%d%d 1) a%d%d)", y, x, y - 1, x); fprintf(fp, " (= (+ a%d%d 1) a%d%d)", y, x, y + 1, x); fprintf(fp, " (= (+ a%d%d 1) a%d%d)", y, x, y, x - 1); fprintf(fp, " (= (+ a%d%d 1) a%d%d)", y, x, y, x + 1); fprintf(fp, ")))\n"); } } // x축일 경우 for (y = 1; y <= heit; y = heit) { for (x = 2; x <= wid - 1; x++) { if (y == 1) { fprintf(fp, "(assert (and (or"); fprintf(fp, " (= (- a%d%d 1) a%d%d)", y, x, y, x - 1); fprintf(fp, " (= (- a%d%d 1) a%d%d)", y, x, y + 1, x); fprintf(fp, " (= (- a%d%d 1) a%d%d)", y, x, y, x + 1); fprintf(fp, ") (or"); fprintf(fp, " (= (+ a%d%d 1) a%d%d)", y, x, y, x - 1); fprintf(fp, " (= (+ a%d%d 1) a%d%d)", y, x, y + 1, x); fprintf(fp, " (= (+ a%d%d 1) a%d%d)", y, x, y, x + 1); fprintf(fp, ")))\n"); } else if (y == heit) { fprintf(fp, "(assert (and (or"); fprintf(fp, " (= (- a%d%d 1) a%d%d)", y, x, y - 1, x); fprintf(fp, " (= (- a%d%d 1) a%d%d)", y, x, y, x + 1); fprintf(fp, " (= (- a%d%d 1) a%d%d)", y, x, y, x - 1); fprintf(fp, ") (or"); fprintf(fp, " (= (+ a%d%d 1) a%d%d)", y, x, y - 1, x); fprintf(fp, " (= (+ a%d%d 1) a%d%d)", y, x, y, x + 1); fprintf(fp, " (= (+ a%d%d 1) a%d%d)", y, x, y, x - 1); fprintf(fp, ")))\n"); } } if (x == wid && y == heit) break; } // y축일 경우 for (x = 1; x <= wid; x = wid) { for (y = 2; y <= heit - 1; y++) { if (x == 1) { fprintf(fp, "(assert (and (or"); fprintf(fp, " (= (- a%d%d 1) a%d%d)", y, x, y, x + 1); fprintf(fp, " (= (- a%d%d 1) a%d%d)", y, x, y + 1, x); fprintf(fp, " (= (- a%d%d 1) a%d%d)", y, x, y - 1, x); fprintf(fp, ") (or"); fprintf(fp, " (= (+ a%d%d 1) a%d%d)", y, x, y, x + 1); fprintf(fp, " (= (+ a%d%d 1) a%d%d)", y, x, y + 1, x); fprintf(fp, " (= (+ a%d%d 1) a%d%d)", y, x, y - 1, x); fprintf(fp, ")))\n"); } else if (x == wid) { fprintf(fp, "(assert (and (or"); fprintf(fp, " (= (- a%d%d 1) a%d%d)", y, x, y, x - 1); fprintf(fp, " (= (- a%d%d 1) a%d%d)", y, x, y + 1, x); fprintf(fp, " (= (- a%d%d 1) a%d%d)", y, x, y - 1, x); fprintf(fp, ") (or"); fprintf(fp, " (= (+ a%d%d 1) a%d%d)", y, x, y, x - 1); fprintf(fp, " (= (+ a%d%d 1) a%d%d)", y, x, y + 1, x); fprintf(fp, " (= (+ a%d%d 1) a%d%d)", y, x, y - 1, x); fprintf(fp, ")))\n"); } } if (x == wid && y == heit) break; } // 코너일 경우 for (y = 1; y <= heit; y = y+heit-1) { for (x = 1; x <= wid; x = x+wid-1) { if (x == y) { if (x == 1) { fprintf(fp, "(assert (and (or"); fprintf(fp, " (= (- a%d%d 1) a%d%d)", y, x, y + 1, x); fprintf(fp, " (= (- a%d%d 1) a%d%d)", y, x, y, x + 1); fprintf(fp, ") (or"); fprintf(fp, " (= (+ a%d%d 1) a%d%d)", y, x, y + 1, x); fprintf(fp, " (= (+ a%d%d 1) a%d%d)", y, x, y, x + 1); fprintf(fp, ")))\n"); } else { fprintf(fp, "(assert (and (or"); fprintf(fp, " (= (- a%d%d 1) a%d%d)", y, x, y - 1, x); fprintf(fp, " (= (- a%d%d 1) a%d%d)", y, x, y, x - 1); fprintf(fp, ") (or"); fprintf(fp, " (= (+ a%d%d 1) a%d%d)", y, x, y - 1, x); fprintf(fp, " (= (+ a%d%d 1) a%d%d)", y, x, y, x - 1); fprintf(fp, ")))\n"); } } else { if (x > y) { fprintf(fp, "(assert (and (or"); fprintf(fp, " (= (- a%d%d 1) a%d%d)", y, x, y + 1, x); fprintf(fp, " (= (- a%d%d 1) a%d%d)", y, x, y, x - 1); fprintf(fp, ") (or"); fprintf(fp, " (= (+ a%d%d 1) a%d%d)", y, x, y + 1, x); fprintf(fp, " (= (+ a%d%d 1) a%d%d)", y, x, y, x - 1); fprintf(fp, ")))\n"); } else { fprintf(fp, "(assert (and (or"); fprintf(fp, " (= (- a%d%d 1) a%d%d)", y, x, y - 1, x); fprintf(fp, " (= (- a%d%d 1) a%d%d)", y, x, y, x + 1); fprintf(fp, ") (or"); fprintf(fp, " (= (+ a%d%d 1) a%d%d)", y, x, y - 1, x); fprintf(fp, " (= (+ a%d%d 1) a%d%d)", y, x, y, x + 1); fprintf(fp, ")))\n"); } } if (x == wid) break; } if (x == wid && y == heit) break; } fprintf(fp, "(check-sat)\n(get-model)\n"); fclose(fp); i = 0; j = 0; int k, temp2; char board[heit][wid]; char temp1[10]; char b[128]; char s[128]; char t[128]; char buf[128]; FILE* fpp = popen("z3 formula", "r"); fscanf(fpp, "%s", buf); printf("%s\n", buf); if (strcmp(buf, "sat") != 0) { printf("No Solution.\n"); pclose(fpp); return -1; } fscanf(fpp, "%s", b); for (k = 0; k < heit * wid; k++) { fscanf(fpp, "%s %s %s %s %s", b, s, b, b, t); i = s[1] - '0'; j = s[2] - '0'; int length = strlen(t); for (int i = 0; i < length - 1; i++) { temp1[i] = t[i]; } temp1[length - 1] = '\0'; temp2 = atoi(temp1); board[i][j] = temp2; } for (i = 1; i <= heit; i++) { for (j = 1; j <= wid; j++) { printf("%2d ", board[i][j]); } printf("\n"); } }
C
#include "SeqList.h" #include <Windows.h> int main(){ SeqList sl; SeqListInit(&sl, 2); printf("˳"); SeqListPushBack(&sl, 1); SeqListPushBack(&sl, 2); SeqListPushBack(&sl, 3); SeqListPrint(&sl); printf("ͷ0"); SeqListPushFront(&sl, 0); SeqListPrint(&sl); printf("ͷɾ"); SeqListPopFront(&sl); SeqListPrint(&sl); SeqListFind(&sl, 3);//ҵ± SeqListDestory(&sl); system("pause"); return 0; }
C
// To draw a simple shaded scene consisting of a tea pot on a table. // Define suitably the position and properties of the light source // along with the properties of the surfaces of the solid object used in the scene. #include <stdio.h> #include <GL/glut.h> void wall() { glPushMatrix(); glScalef(2, 0.05, 2); glutSolidCube(2); glPopMatrix(); glPushMatrix(); glTranslatef(-2, 2, 0); glRotatef(-90, 0, 0, 1); glScalef(2, 0.05, 2); glutSolidCube(2); glPopMatrix(); glPushMatrix(); glTranslatef(0, 2, -2); glRotatef(90, 1, 0, 0); glScalef(2, 0.05, 2); glutSolidCube(2); glPopMatrix(); } void table() { glPushMatrix(); glTranslatef(0, 0.5, 0); glScalef(1, 0.05, 1); glutSolidCube(2); glPopMatrix(); glPushMatrix(); glTranslatef(-0.8, 0.2, 0.8); glScalef(0.1, 0.25, 0.1); glutSolidCube(2); glPopMatrix(); glPushMatrix(); glTranslatef(0.8, 0.2, 0.8); glScalef(0.1, 0.25, 0.1); glutSolidCube(2); glPopMatrix(); glPushMatrix(); glTranslatef(0.8, 0.2, -0.8); glScalef(0.1, 0.25, 0.1); glutSolidCube(2); glPopMatrix(); glPushMatrix(); glTranslatef(-0.8, 0.2, -0.8); glScalef(0.1, 0.25, 0.1); glutSolidCube(2); glPopMatrix(); } void teapot() { glPushMatrix(); glTranslatef(0, 1.3, 0); glRotatef(45, 0, 1, 0); glutSolidTeapot(1); glPopMatrix(); } void display(void) { float amb[] = {1, 0, 0, 1}; float pos[] = {2, 4, 1}; glMaterialfv(GL_FRONT, GL_AMBIENT, amb); glLightfv(GL_LIGHT0, GL_POSITION, pos); glLightfv(GL_LIGHT0, GL_AMBIENT, amb); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-4, 4, -4, 4, -10, 10); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(2.5, 1, 2, 0, 0.5, 0, 0, 1, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearColor(1, 1, 1, 1); wall(); table(); teapot(); glFlush(); } int main(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_DEPTH | GLUT_RGB); glutInitWindowSize(600, 600); glutCreateWindow("1JS18CS403 - Dhruva V : TEAPOT"); glutDisplayFunc(display); glEnable(GL_DEPTH_TEST); glEnable(GL_SMOOTH); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_NORMALIZE); glutMainLoop(); } // dhruvawara@dbuntu:~/6th-SEM-LAB/CG/6th Program$ cc Program6.c -lglut -lGL -lGLU -lm -o Program6.out // dhruvawara@dbuntu:~/6th-SEM-LAB/CG/6th Program$ ./Program6.out
C
#include "types.h" #include "user.h" #include "stat.h" #include "fcntl.h" #include "ipc.h" int itr = 0; // Key value iterator char * strcat(char *a,char *b) { char *t = malloc(200); int i = 0,k = 0; while(a) t[i++] = a[k++]; k = 0; while(a) t[i++] = b[k++]; t[i] = '\0'; return t; } char * ktof(int k) { int i = 0; char *str = (char *) malloc(sizeof(int) * 100); while(k) { int d = k % 10; str[i++] = d + '0'; k /= 10; } str[i] = '\0'; return str; } int shmat(int k,int *fd,int mode) { *fd = open(ktof(k),mode); if(*fd <= 0) return -1; return *fd; } int shmget(int k,int *fd) { *fd = open(ktof(k),O_CREATE); if(*fd <= 0 ) // Failure return -1; return *fd; } int find(int k) { return 0; } int toInt(char *a) { int i = strlen(a)-1; int ans = 0; int weight = 1; while(i>=0) { int dig = a[i] - '0'; ans += dig * weight; weight *= 10; i--; } return ans; } int isInt(char *a) { while(*a) { if(*a >= '0' && *a <= '9'){} else return 0; a++; } return 1; } void man() { char man[] = "---------- IPC MANUAL DOCUMENTATION ------------\nList of Commands :\n\nSHARED MEMORY : \n\nipc shmget [key-id] -----> Create a Shared Memory Segment with key = key-id\n\n\nipc shmdt [key-id] -----> Delete the Created Shared memory segment\n\n\nipc shmat [key-id] [mode (RD/WR)] -----> Attach to the Shared Memory segment and Read or Write with respect to the given mode specs\n\n--------------------------------------------------\n"; printf(1,"%s",man); } int main(int argc,char **argv) { //Decode syntax if(argc == 2 && !strcmp(argv[1],"man")) { man(); goto exit; } else if( (argc == 3 || argc == 4) && ( !strcmp(argv[1],"shmat") || !strcmp(argv[1],"shmget") || !strcmp(argv[1],"shmdt"))&& isInt(argv[2])) { int key = toInt(argv[2]); int fd = -1; //FILE DESCRIPTOR if(!strcmp(argv[1],"shmat")) { if(argc == 3 || ( strcmp(argv[3],"RD") && strcmp(argv[3],"WR") && strcmp(argv[3],"RDWR")) ) goto bad; int mode; if(!strcmp(argv[3],"RD")) mode = O_RDONLY; else if(!strcmp(argv[3],"WR")) mode = O_WRONLY; else mode = O_RDWR; if(shmat(key,&fd,mode) != -1) { if(mode == O_WRONLY) { printf(1,"ipc write > "); char c; while(read(0,&c,1) && c!='\n') write(fd,&c,1); } if(mode == O_RDONLY) { printf(1,"Enter bytes to read > "); int i = 0; char str[20],c; while(read(0,&c,1) && c!='\n' &&write(fd,&c,1)) str[i++] = c; int bytes = toInt(str); printf(1,"ipc read > "); while(read(fd,&c,1) == 1 && bytes--) printf(1,"%c",c); } printf(1,"\n"); } else printf(1,"Attach failed\n"); } else if(!strcmp(argv[1],"shmget")) { printf(1,"Shared memory is created with key : %d\n",key); int shmid = shmget(key,&fd); printf(1,"SHMID : %d\n",shmid); } else { if(shmget(key,&fd) == -1) printf(1,"Detach Failure - fatal error (shm not found)\n"); else { char **args = malloc(2); *args = malloc(100); args[0] = "rm\0"; args[1] = ktof(key); printf(1,"Detach Successful\n"); exec("rm",args); } } goto exit; } else goto bad; bad : printf(1,"Syntax Error : use \"ipc [mode] [number] [RD.WR]\" use \"ipc man \" for help\n"); exit : exit(); }
C
/** * \file generator.c * * \brief Génère des fichiers de taille et de contenu aléatoire. * */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> int main(int argc, char ** argv) { if(argc != 2) { fprintf(stderr, "Error : Give filename\n"); } int fd = open(argv[1], O_WRONLY | O_CREAT); srand(time(NULL)); int length = rand() % 10000; for(int i=0; i<length; i++) { int r = rand()%25 + 65; char c = (char)r; write(fd,&c,1); } close(fd); }
C
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <conio.h> int main(int argc, char const *argv[]) { system("cls"); argv=argv; argc=argc; float inteiro; float fracao; float partes; printf (" Digite o valor do inteiro:"); scanf ("%f",&inteiro); printf (" Digite a quantidade de partes:"); scanf ("%f",&partes); fracao=inteiro/partes; printf ("\n A fracao e: %f ",fracao); getch(); return 0; }
C
#include <stdio.h> #include <stdlib.h> char ch, filename[50]; int n; FILE *fp; void main (void) { printf("\nPlease specify the file you would like to count the characters of: "); scanf("%s", filename); if ( (fp = fopen(filename, "r")) == NULL) { fprintf(stderr, "\nError opening file specifed"); exit(1); } while (1) { ch = fgetc(fp); if(feof(fp)) break; if(ch > 31 && ch < 127) n++; } printf("There are %d characters in this file\n", n); fclose(fp); }
C
#include <stdio.h> #include "cursor.h" void PrintList_cur( const List L ) { Position P = Header_cur( L ); if( IsEmpty_cur( L ) ) printf( "Empty list\n" ); else { do { P = Advance_cur( P ); printf( "%d ", Retrieve_cur( P ) ); } while( !IsLast_cur( P, L ) ); printf( "\n" ); } } void testcurs( ) { List L; Position P; int i; InitializeCursorSpace( ); L = MakeEmpty_cur( 0 ); P = Header_cur( L ); PrintList_cur( L ); for( i = 0; i < 10; i++ ) { Insert_cur( i, L, P ); PrintList_cur( L ); P = Advance_cur( P ); } for( i = 0; i < 10; i+= 2 ) Delete_cur( i, L ); for( i = 0; i < 10; i++ ) if( ( i % 2 == 0 ) == ( Find_cur( i, L ) != 0 ) ) printf( "Find fails\n" ); printf( "Finished deletions\n" ); PrintList_cur( L ); DeleteList_cur( L ); return ; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* sh_perror2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jmartel <jmartel@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/13 14:41:27 by jmartel #+# #+# */ /* Updated: 2019/06/11 14:20:28 by jmartel ### ########.fr */ /* */ /* ************************************************************************** */ #include "sh_21.h" int sh_perror2(const char *error, const char *prefix, const char *suffix) { ft_dprintf(2, "%s%s: %s: %s: %s%s\n", SH_ERR_COLOR, SH_NAME, prefix, error, suffix, COLOR_END); return (FAILURE); } int sh_perror2_err( const char *error, const char *prefix, const char *suffix) { sh_perror2(error, prefix, suffix); return (ERROR); } void *sh_perror2n(const char *error, const char *prefix, const char *suffix) { sh_perror2(error, prefix, suffix); return (NULL); } int sh_perror2_err_fd( int fd, const char *error, const char *prefix, const char *suffix) { sh_perror2_fd(fd, error, prefix, suffix); return (ERROR); } void *sh_perror2n_fd( int fd, const char *error, const char *prefix, const char *suffix) { ft_dprintf(fd, "%s%s: %s: %s: %s%s\n", SH_ERR_COLOR, SH_NAME, prefix, error, suffix, COLOR_END); if (suffix && *suffix) ft_dprintf(fd, "%s%s: %s : %s%s\n", SH_ERR_COLOR, SH_NAME, error, suffix, COLOR_END); else ft_dprintf(fd, "%s%s: %s%s\n", SH_ERR_COLOR, SH_NAME, error, COLOR_END); return (NULL); }
C
int i; int j; int gcd(int u, int v) { if (v==0) return u; else return gcd(v, u-u/v*v); /* u-u/v*v == u mod v */ } void main(void) { int x; int y; /*x = input(x); y = input(y);*/ output(gcd(x, y)); }
C
#include "header.h" #include "string.h" #define ColorsSize (sizeof colors/sizeof *colors) enum {MinIn = 5, MaxIn = 12}; enum Colors {BLACK, BROWN, RED, ORANGE, YELLOW, GREEN, BLUE, VIOLET, GREY, WHITE, GOLD, SILVER, UNKNOWN}; struct colorList { char *color_name; enum Colors id; }colors[] = {{"black", BLACK}, {"brown", BROWN}, {"red", RED}, {"orange", ORANGE}, {"yellow", YELLOW}, {"green", GREEN}, {"blue", BLUE}, {"violet", VIOLET}, {"grey", GREY}, {"white", WHITE}, {"gold", GOLD}, {"silver", SILVER}}; int FindColor (char *value) { int i; char LowerColor[MaxIn] = ""; // array to store all the input in lowercase UpperToLower (LowerColor, value); for (i = 0; i < (int)ColorsSize; ++i) if (*LowerColor == *(colors[i].color_name)) if (!CompareColor(colors[i].color_name, LowerColor)) // checks for error return i; return -1; }
C
# C #include <stdio.h> int main(){ int i,j; for(i=1;i<=6;i++){ for(j=0;j<=i-1;j++){ printf("%c",'A'+(i-1)); } printf("\n"); } return 0; }
C
int ft_memcmp(const void *s1, const void *s2, size_t n) { size_t i; unsigned char *s1b; unsigned char *s2b; s1b = (unsigned char *)s1; s2b = (unsigned char *)s2; i = 0; if (n == 0) return (0); while (i < n && s1b[i] == s2b[i]) i++; if (i == n) i--; return (s1b[i] - s2b[i]); }
C
/* Joseph Soukup Steven Mulvey */ #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include "537malloc.h" #include "537tree.h" #include <stdint.h> tree *maple = NULL; tree * constructTree() { tree * maple = malloc(sizeof(tree)); maple->root = NULL; return maple; } void *malloc537(size_t size) { if (maple == NULL){ maple = constructTree(); } int * temp; tuple * t = malloc(sizeof(tuple)); t->len = size; temp = (int*)malloc(size); t->addr = (uintptr_t)&(*temp); if (size == 0) { printf("Warning: size is 0!"); } tuple e = *t; insert(maple, e); return temp; } void free537(void *ptr) { // Check to make sure malloc537 was used to malloc Node * needsFree = search537(ptr); if (needsFree == NULL) { printf("Error: Memory has not been previously allocated at this address"); exit(-1); } if (needsFree->free == 1) { printf("Error: Attempting to double free"); exit(-1); } else if (needsFree->free == 0){ needsFree->free = 1; free(ptr); } } struct Node *search537(uintptr_t *addr) { Node *temp = maple->root; while (temp != NULL) { if (temp->data.addr > (uintptr_t)&(*addr)) { //printf("Is smaller than"); if (temp->left == NULL) { printf("Warning: Memory address 2 not allocated"); break; } else { temp = temp->left; } } else if (temp->data.addr == (uintptr_t)&(*addr)) { //printf("Is equal to"); break; } else { //printf("Is larger than"); if (temp->right == NULL) { uintptr_t add = temp->data.addr + temp->data.len; if (add > (uintptr_t)&(*addr)){ printf("The memory is allocated but not a node"); } else { printf("Warning: Memory address too big"); break; } } else { temp = temp->right; } } } return temp; } void *realloc537(void *ptr, size_t size) { Node *temp = maple->root; if (ptr == NULL) { return malloc537(size); } else if (size == 0) { if (ptr != NULL) { free537(ptr); return ptr; } } else { Node *node = search537(ptr); deleteByVal(maple, node->data); int * temp; tuple * t = malloc(sizeof(tuple)); t->len = size; temp = (int*)malloc(size); t->addr = (uintptr_t)&(*temp); if (size == 0) { printf("Warning: size is 0!"); } tuple e = *t; insert(maple, e); } return temp; } void memcheck537(void *ptr, size_t size) { Node *temp = maple->root; uintptr_t ref = (uintptr_t)ptr + size; while (temp != NULL) { if (((uintptr_t)ptr + size < temp->data.addr + temp->data.len) || ((uintptr_t)ptr < temp->data.addr)) { if (temp->left == NULL) { printf("Checked memory is partially or fully unallocated.\n"); exit(-1); } else temp = temp->left; } else if ((ref == temp->data.addr + temp->data.len) || ((uintptr_t)ptr == temp->data.addr)) { if (temp->free == 0) { printf("Checked memory is allocated.\n"); break; } } else if (((uintptr_t)ptr + size > temp->data.addr + temp->data.len) || ((uintptr_t)ptr > temp->data.addr)) { if (temp->right == NULL) { printf("Checked memory is partially or fully unallocated.\n"); exit(-1); } else temp = temp->right; } } } /* int main () { uintptr_t *test = malloc537(6); memcheck537(test, sizeof(test)); int *five = malloc(5); memcheck537(five, sizeof(five)); }*/
C
#include <stdio.h> #include <math.h> int angle(int fram, int bak){ int vinkel; double kvot; double delta; double mellan = 20; //Avståndet mellan sensorerna delta = fram - bak; kvot = delta/mellan; vinkel = atan(kvot)*180/3.14; //int på vinkel om man vill ha heltal på graderna. //kanske måste lägga till en IF-sats här om vi vill invertera vinkel beroende på vilken sida man mäter på. //typ If left -> vinkel = vinkel * (-1) return vinkel; } int mittpunkt(int vinkel, int fram_h, int fram_v, int bak_h, int bak_v){ int hyp_h; int hyp_v; //hypotinusan från centrum int kat_h; //katet = lägden från centrum av roboten till vägg int kat_v; hyp_h = ((fram_h + bak_h) / 2) + 10; // + 10 är längden från kanten till centrum på roboten hyp_v = ((fram_v + bak_v) / 2) + 10; kat_h = hyp_h * cos(vinkel*3.14/180);//Dessa kan slås ihop, men pedagogiskt just nu. kat_v = hyp_v * cos(vinkel*3.14/180); return 2; //Vad vill man skicka tillbaka? plus på höger sida minus på vänster eller 0 = väldigt mycket åt vänster 100/255 = väldigt mycket åt höger, eller vill man bara mäta en sida i taget? } int main(int argc, const char * argv[]) { converter(); int vinkel1; int vinkel2; int fram1 = 35; //Testdata int bak1 = 15; int fram2 =35; int bak2 = 55; vinkel1 = angle(fram1,bak1); vinkel2 = angle(fram2,bak2); int position = mittpunkt(vinkel1, fram1, fram2, bak1, bak2); return 0; }
C
#ifndef __OP_TEST_H__ #define __OP_TEST_H__ #include "gtest/gtest.h" #include "../header/op.h" TEST(OpTest, OpEvaluateNonZero) { Op* test = new Op(8); EXPECT_EQ(test->evaluate(), 8); delete test; } TEST(OpTest, OpStringifyNonZero) { Op* test = new Op(24); EXPECT_EQ(test->stringify(), "24"); delete test; } TEST(OpTest, OpEvaluateNegativeInts) { Op* test = new Op(-5); EXPECT_EQ(test->evaluate(), -5); delete test; } TEST(OpTest, OpStringifyNegativeInts) { Op* test = new Op(-47); EXPECT_EQ(test->stringify(), "-47"); delete test; } TEST(OpTest, OpEvaluateNonZeroDouble) { Op* test = new Op(62.7); EXPECT_EQ(test->evaluate(), 62.7); delete test; } TEST(OpTest, OpStringifyNonZeroDouble) { Op* test = new Op(24.7); EXPECT_EQ(test->stringify(), "24.7"); delete test; } TEST(OpTest, OpEvaluateNegativeDouble) { Op* test = new Op(-3.9); EXPECT_EQ(test->evaluate(), -3.9); delete test; } TEST(OpTest, OpStringifyNegativeDouble) { Op* test = new Op(-56.2); EXPECT_EQ(test->stringify(), "-56.2"); delete test; } TEST(OpTest, OpEvaluateZero) { Op* test = new Op(0); EXPECT_EQ(test->evaluate(), 0); delete test; } TEST(OpTest, OpStringifyZero) { Op* test = new Op(0); EXPECT_EQ(test->stringify(), "0"); delete test; } #endif //__OP_TEST_H__
C
/********************************************************************** * Nom ............ : methodes.c * Role ........... : * Auteur ......... : Marvin Lasserre *********************************************************************/ #include <stdio.h> #include <stdlib.h> #include <tgmath.h> #include "real_precision.h" #include "methodes.h" void godunov(const int N, real alpha, real l_border, real r_border, real* anc, real* nouv){ int i = 0; /* Compteur pour le vecteur flux de taille N-1 */ real s = 0.; /* Vitesse du choc */ real f[N-1]; /* Vecteur contenant le flux aux interfaces */ for(i=0;i<N-1;i++){ f[i] = 0.; } for(i=0;i<N-1;i++){ /* printf("anc[%d] = %g\n anc[%d] = %g\n\n", i, anc[i], i+1, anc[i+1]); */ if(anc[i]>anc[i+1]){ /* Cas d'un choc */ s = (anc[i] + anc[i+1]) / 2; if(s<0){ f[i] = anc[i+1]*anc[i+1]/2; } else{ /* Cas d'une rarefaction */ f[i] = anc[i]*anc[i]/2; } } else if(anc[i]<=anc[i+1]){ if(anc[i] > 0){ f[i] = anc[i]*anc[i]/2; } else if(anc[i+1] < 0){ f[i] = anc[i+1]*anc[i+1]/2; } else{ f[i] = 0.; } } else{ fprintf(stderr, "Erreur dans la methode de Godunov\n"); exit(EXIT_FAILURE); } } for(i=1;i<N-1;i++){ /* Resolution */ nouv[i] = anc[i] - alpha*(f[i] - f[i-1]); } nouv[0] = l_border; nouv[N-1] = r_border; }
C
#include <stdio.h> #include <ctype.h> /*GAME CONFIGURATION*/ #define ROWS 6 #define COLUMNS 7 #define OPEN_CELL_ASCII 46 #define COLUMN_LETTER_START 65 #define OPEN_CELL '.' #define PLAYER_1_PIECE 'X' #define PLAYER_2_PIECE 'O' #define COLORED_PLAYER_1_PIECE 'N' #define COLORED_PLAYER_2_PIECE 'B' /*Game board controller*/ /* * Function name : initilizeGameBoard() * Usage : initilizeGameBoard(char board[][]) * Definition : Sets all of the values in board[][] to OPEN_CELL. */ void initilizeGameBoard(char board[][COLUMNS]) { for (int i = 0; i < ROWS; i++) { for (int j = 0; j < COLUMNS; j++) { board[i][j] = OPEN_CELL; } } } /* * Function name : printGameBoard() * Usage : printGameBoard(char board[][]) * Definition : Prints a visual representation of board[][]. */ void printGameBoard(char board[][COLUMNS]) { int rowNum = ROWS; char columnChar = COLUMN_LETTER_START; //Print column letters above board in order a,b,c,d,etc... printf(" "); for (int k = 0; k< COLUMNS; k++) { printf("%c ", columnChar); columnChar++; } printf("\n"); //Print board and row numbers 1,2,3,5,etc... for (int i = 0; i < ROWS; i++) { printf("%i " , rowNum); rowNum--; for (int j = 0; j < COLUMNS; j++) { char cellElement = board[i][j]; if (cellElement == COLORED_PLAYER_1_PIECE) { printf("\033[0;31m"); printf("%c ", PLAYER_1_PIECE); } else if (cellElement == COLORED_PLAYER_2_PIECE) { printf("\033[0;31m"); printf("%c ", PLAYER_2_PIECE); } else { printf("%c ", cellElement); } printf("\033[0m"); } printf("\n"); } } /* * Function name : isValidMove() * Usage : printGameBoard(char board[][], int column) * Definition : Used to check if board[][] has an open space at int column. * Returns : _Bool representing if dropping a piece into int column is a valid choice. 1 = valid, 0 = not valid. */ _Bool isValidMove(char board[][COLUMNS], int column) { return (board[0][column] == OPEN_CELL); } /* * Function name : findValidMoves() * Usage : findValidMoves(char board[][], int validMoves[]) * Definition : Modifes the validMoves[] array to contain all of the columns that still have open cells in the char board[][]. * Returns : int representing number of valid moves remaining on board[][]. */ int findValidMoves(char board[][COLUMNS], int validMoves[]) { int numberOfValidMoves = 0; for (int c = 0; c < COLUMNS; c++) { if (isValidMove(board, c)) { validMoves[numberOfValidMoves] = c; numberOfValidMoves++; } } return numberOfValidMoves; } /* * Function name : dropPiece() * Usage : dropPiece(char board[][], int column, char piece) * Definition : Sets the the first open row in board[][] at int column to char piece */ void dropPiece(char board[][COLUMNS], int column, char piece) { for (int i = ROWS-1; i >= 0; i--) { char element = board[i][column]; if (element == OPEN_CELL) { board[i][column] = piece; return; } } } /* * Function name : isWinner() * Usage : iswinner(char board[][], char piece) * Definition : Checks if a player has won by looking for horizontal, vertical, right diagonal, and left diagonal chains of 4 identical pieces in a row * Returns: : _Bool representing whether the player who dropped char piece wins the game. 1 = player wins, 0 = player hasn't won. */ _Bool isWinner(char board[][COLUMNS], char piece) { int winningChunk[4]; int winningChunkIndex; //Horizontal for (int i = 0; i < COLUMNS - 3; i++) { for (int j = 0; j < ROWS; j++) { if (board[j][i] == piece && board[j][i+1] == piece && board[j][i+2] == piece && board[j][i+3] == piece) { for (int k = 0; k < 4; k++) { if (piece == PLAYER_1_PIECE) { board[j][i + k] = COLORED_PLAYER_1_PIECE; } else { board[j][i + k] = COLORED_PLAYER_2_PIECE; } } return 1; } } } //Vertical for (int i = ROWS-1; i >= 3; i--) { for (int j = 0; j < COLUMNS; j++) { if (board[i][j] == piece && board[i-1][j] == piece && board[i-2][j] == piece && board[i-3][j] == piece) { for (int k = 3; k >= 0; k--) { if (piece == PLAYER_1_PIECE) { board[i - k][j] = COLORED_PLAYER_1_PIECE; } else { board[i - k][j] = COLORED_PLAYER_2_PIECE; } } return 1; } } } //Right diagonal for (int i = ROWS-1; i >= 3; i--) { for (int j = 0; j < COLUMNS - 3; j++) { if (board[i][j] == piece && board[i-1][j+1] == piece && board[i-2][j+2] == piece && board[i-3][j+3] == piece) { for (int k = 0; k < 4; k++) { if (piece == PLAYER_1_PIECE) { board[i - k][j + k] = COLORED_PLAYER_1_PIECE; } else { board[i - k][j + k] = COLORED_PLAYER_2_PIECE; } } return 1; } } } //Left diagonal for (int i = ROWS-1; i >= 3; i--) { for (int j = COLUMNS-1; j >= 3; j--) { if (board[i][j] == piece && board[i-1][j-1] == piece && board[i-2][j-2] == piece && board[i-3][j-3] == piece) { for (int k = 0; k < 4; k++) { if (piece == PLAYER_1_PIECE) { board[i - k][j - k] = COLORED_PLAYER_1_PIECE; } else { board[i - k][j - k] = COLORED_PLAYER_2_PIECE; } } return 1; } } } return 0; } /* * Function name : getColumnIndex() * Usage : getColumnIndex(char column) * Definition : Coverts the char column to an index on a gameBoard[][] 2d array. * Returns : An int which is the column index corresponding to char column. */ int getColumnIndex(char column) { char columnLetter = COLUMN_LETTER_START; for (int i = 0; i < COLUMNS; i++) { if (columnLetter == column) { return i; } columnLetter++; } return -1; } /* * Function name : getColumnLetter() * Usage : getColumnLetter(int columnIndex) * Definition : Finds the letter corresponding to the int columnIndex argument. * Returns : A char which is the letter corresponding to int columnIndex (letter above column on board). */ char getColumnLetter(int columnIndex) { char columnLetter = (char) (COLUMN_LETTER_START + columnIndex); columnLetter = toupper(columnLetter); return columnLetter; } /* * Function name : cloneBoard() * Usage : cloneBoard(char board[][], char newBoard[][]) * Definition : Copies all of the elements from board[][] into newBoard[][] creating a clone. */ void cloneBoard(char board[][COLUMNS], char newBoard[][COLUMNS]) { for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLUMNS; c++) { newBoard[r][c] = board[r][c]; } } } /*AI controller*/ /* * Function name : getPiecesInChunk() * Usage : getColumnIndex(char chunk[], char piece) * Definition : Counts how many char piece are in char chunk[] and returns the count. * Returns : An int representing the number of char piece in char chunk[]. */ int getPiecesInChunk(char chunk[4], char piece) { int count = 0; for (int i = 0; i < 4; i++) { char element = chunk[i]; if (chunk[i] == piece) { count++; } } return count; } /* * Function name : resetChunk() * Usage : resetChunk(char chunk[4]) * Definition : Sets every value in char chunk[4] to 'm' which is a character that is not used in the game so it represents nothing. */ void resetChunk(char chunk[4]) { for (int i = 0; i < 4; i++) { chunk[i] = 'm'; } } /* * Function name : getChunkValue() * Usage : getChunkValue(char chunk[4], char piece) * Definition : Calculates the value of a chunk containing game pieces and blank spaces and returns this value. This function is used by the ai to determine where it should place it's piece. * Returns : An int representing the value the ai placed on char chunk[]. */ int getChunkValue(char chunk[4], char piece) { int chunkValue = 0; //Get #pieces, #opencells, #playerpieces in chunk int piecesInChunk = getPiecesInChunk(chunk, piece); int numberOfOpenCells = getPiecesInChunk(chunk, OPEN_CELL); int playerPiecesInChunk; if (piece == PLAYER_1_PIECE) { playerPiecesInChunk = getPiecesInChunk(chunk, PLAYER_2_PIECE); } else { playerPiecesInChunk = getPiecesInChunk(chunk, PLAYER_1_PIECE); } //Value the chunk based on what it contains if (piecesInChunk == 2 && numberOfOpenCells == 2) { chunkValue+= 1; } else if (piecesInChunk == 3 && numberOfOpenCells == 1) { chunkValue += 5; } else if (piecesInChunk == 4) { chunkValue += 100000000; } if (playerPiecesInChunk == 3 && numberOfOpenCells == 1) { chunkValue -= 1000000; } else if (playerPiecesInChunk == 2 && numberOfOpenCells == 2) { chunkValue -= 100; } return chunkValue; } /* * Function name : findBoardValue() * Usage : findBoardValue(char board[][], char piece) * Definition : Iterates through the board creating arrays of size 4 and fills them with all possible locations a connect 4 could be found. It then collects the total value of every array and returns this value. * Returns : An int representing the total value the ai places on char board[][]. */ int findBoardValue(char board[][COLUMNS], char piece) { int boardValue = 0; //Check horizontal direction for (int r = 0; r < ROWS; r++) { char chunk[4]; resetChunk(chunk); for (int c = 0; c < COLUMNS - 3; c++) { for (int i = 0; i < 4; i++) { chunk[i] = board[r][c + i]; } boardValue += getChunkValue(chunk, piece); resetChunk(chunk); } } //Check vertical direction for (int c = 0; c < COLUMNS; c++) { char chunk[4]; resetChunk(chunk); for (int r = ROWS-1; r >= 3; r--) { for (int i = 0; i < 4; i++) { chunk[i] = board[r - i][c]; } boardValue += getChunkValue(chunk, piece); resetChunk(chunk); } } //Check right diagonal for (int r = ROWS - 1; r >= 3; r--) { char chunk[4]; resetChunk(chunk); for (int c = 0; c < COLUMNS - 3; c++) { for (int i = 0; i < 4; i++) { chunk[i] = board[r - i][c + i]; } boardValue += getChunkValue(chunk, piece); resetChunk(chunk); } } //Check left diagonal for (int r = ROWS - 1; r > ROWS-3; r--) { char chunk[4]; resetChunk(chunk); for (int c = COLUMNS-1; c >= 3; c--) { for (int i = 0; i < 4; i++) { chunk[i] = board[r - i][c - i]; } boardValue += getChunkValue(chunk, piece); resetChunk(chunk); } } return boardValue; } /* * Function name : takeTurn() * Usage : takeTurn(char board[][], char piece) * Definition : Iterates through every valid move the ai could make during their turn, performs this move and then calculates the value of the resulting board. From every board value it chooses the highest one and makes its final move based on this one. * Returns : A char that corresponds to the letter of the column that the ai dropped their piece into. */ char takeTurn(char board[][COLUMNS], char piece) { printf("Taking turn\n"); //Variables for determining highest board value int validMoves[COLUMNS]; int numberOfValidMoves = findValidMoves(board, validMoves); int bestMoveChoice = -1; int highestBoardValue; if (numberOfValidMoves > 0) { //Iterate through valid moves for (int i = 0; i < numberOfValidMoves; i++) { //Clone the board, and make the move char clonedBoard[ROWS][COLUMNS]; cloneBoard(board, clonedBoard); dropPiece(clonedBoard, validMoves[i], piece); int boardValue = findBoardValue(clonedBoard, piece); /* Compare board values, choosing the move that produced the highest one */ if (bestMoveChoice == -1 || boardValue > highestBoardValue) { highestBoardValue = boardValue; bestMoveChoice = validMoves[i]; } } //Drop the piece at the best choice location printf("Best move choice: %i\n", bestMoveChoice); dropPiece(board, bestMoveChoice, piece); highestBoardValue = 0; return getColumnLetter(bestMoveChoice); } return -1; } /*Game controller*/ /* * Function name : printMoveLog() * Usage : printMoveLog(char log[], int turns) * Definition : Prints a formatted list of the turns that took place in the game. */ void printMoveLog(char log[], int turns) { printf("Moves: ["); for (int i = 0; i < turns; i++) { printf("%c", log[i]); if (i != (turns - 1)) { printf(", "); } } printf("]\n"); } /* * Function name : newGame() * Usage : newGame() * Definition : Starts a new game and directs gameplay. */ char currentPiece = PLAYER_1_PIECE; void newGame(void) { //Main game loop while (1) { //Player choice, used for char inputs char playerChoice; printf("New game: Y/N\n"); scanf(" %c", &playerChoice); playerChoice = tolower(playerChoice); if (playerChoice == 'y') { _Bool validPiece = 0; char playerPiece, aiPiece; while (!validPiece) { printf("Select your piece: %c/%c, or type 'N' to quit\n", PLAYER_1_PIECE, PLAYER_2_PIECE); scanf(" %c", &playerChoice); playerChoice = toupper(playerChoice); if (playerChoice == PLAYER_2_PIECE) { printf("HERE\n"); playerPiece = PLAYER_2_PIECE; aiPiece = PLAYER_1_PIECE; validPiece = 1; } else if (playerChoice == PLAYER_1_PIECE) { playerPiece = PLAYER_1_PIECE; aiPiece = PLAYER_2_PIECE; validPiece = 1; } else if (playerChoice == 'N') { return; } else { printf("Invalid choice\n"); } } //Setup gameboard char gameBoard[ROWS][COLUMNS]; initilizeGameBoard(gameBoard); printGameBoard(gameBoard); //Round variables _Bool hasWon = 0, aiHasTakenTurn = 0; int turnNumber = 0; char moveLog[COLUMNS*ROWS]; while (!hasWon) { //If the ai is player 1, it goes first if (playerPiece == PLAYER_2_PIECE) { //AI takes turn char aiTargetColumn = takeTurn(gameBoard, aiPiece); if (aiTargetColumn != -1) { moveLog[turnNumber] = aiTargetColumn; turnNumber++; } aiHasTakenTurn = 1; hasWon = isWinner(gameBoard, aiPiece); if (hasWon) { printGameBoard(gameBoard); printf("AI WINS!!!\n"); printMoveLog(moveLog, turnNumber); break; } } //Check if there is atleast one valid move remaining int validMoves[COLUMNS]; int numValidMoves = findValidMoves(gameBoard, validMoves); if (numValidMoves == 0) { printf("DRAW!!!\n"); break; } //Player takes turn printf("Your turn: \n"); scanf(" %c", &playerChoice); playerChoice = toupper(playerChoice); /*Convert the player's char input (column letter) to gameboard column index */ int playerTargetColumn; playerTargetColumn = getColumnIndex(playerChoice); while (playerTargetColumn == -1 || !isValidMove(gameBoard, playerTargetColumn)) { printf("Invalid column choice\n"); printf("Your turn: \n"); printGameBoard(gameBoard); scanf(" %c", &playerChoice); playerChoice = toupper(playerChoice); playerTargetColumn = getColumnIndex(playerChoice); } //dropPiece(gameBoard, playerTargetColumn, playerPiece); dropPiece(gameBoard, playerTargetColumn, playerPiece); moveLog[turnNumber] =playerChoice; turnNumber++; hasWon = isWinner(gameBoard, playerPiece); if (hasWon) { printGameBoard(gameBoard); printf("YOU WIN!!!\n"); printMoveLog(moveLog, turnNumber); break; } if (!aiHasTakenTurn) { char aiTargetColumn = takeTurn(gameBoard, aiPiece); aiHasTakenTurn = 1; if (aiTargetColumn != -1) { moveLog[turnNumber] = aiTargetColumn; turnNumber++; } hasWon = isWinner(gameBoard, aiPiece); if (hasWon) { printGameBoard(gameBoard); printf("AI WINS!!!\n"); printMoveLog(moveLog, turnNumber); break; } } printGameBoard(gameBoard); aiHasTakenTurn = 0; } } else { return; } } } /* Main */ int main() { newGame(); return 0; }
C
#include <stdio.h> #include <signal.h> #include <unistd.h> struct sigaction newact; struct sigaction oldact; void sigint_handler(int signo); int main() { newact.sa_handler = sigint_handler; // 시그널 처리기 지정 sigfillset(&newact.sa_mask); // 모든 시그널을 차단하도록 mask // SIGINT의 처리 액션을 새로 지정, oldact에 기존 처리 액션을 저장 sigaction(SIGINT, &newact, &oldact); while(1) { printf("Press 'Ctrl-C'!\n"); sleep(1); } } /* SIGINT 처리 함수 */ void sigint_handler(int signo) { printf("No.%d Signal process!\n", signo); printf("If press again, program end..\n"); sigaction(SIGINT, &oldact, NULL); // 기존 처리 액션으로 변경 }
C
#include <random> double* weights(int n); double randomDouble(double end); double* weights(int n){ double *weight = new double[n]; weight[0] = randomDouble(1); double limit = 1 - weight[0]; for (int i = 1; i < n - 1; ++i){ weight[i] = randomDouble(limit); limit -= weight[i]; } weight[n - 1] = limit; return weight; } // This function only generates in (0, end) double randomDouble(double end){ random_device rd; mt19937 gen(rd()); uniform_real_distribution<> dis(0, end); return dis(gen); }
C
/** ============================================================ * File: main.c * Author: Mihai Cornel mhcrnl@gmail.com 0722270796 * System: Ubuntu 16.04 Code::Blocks 13.12 gcc version 5.4.0 * Fedora 23 Code::Blocks 16.01 gcc version 5.3.1 * =================================================================*/ #include <stdio.h> #include <stdlib.h> #include "cpointer.h" int main() { printf("Hello world!\n"); puts("Introduce-ti cate numere doriti pt a fi comparate si gasit\ numarul cel mai mare pt a inchide introd. -1"); int number; int max=-100000; scanf("%d", &number); while(number != -1){ if(number>max) max=number; scanf("%d", &number); } printf("Cel mai mare numar este %d.\n", max); pointerC(); return 0; }
C
/* Filename: functions.h Author: Parker Hague Course: Operating Systems - CS4323 Assignment: Assignment00 Due: Feb. 4th, 2021, 11:59 PM Submitted: Nov. 30th, 2020 This file is a header file that serves to make several functions and variables global for multi file use. Includes function prototypes, external variable declarations, and library imports. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <ctype.h> // struct to hold player information struct Info{ char playerName[256]; char date[256]; int numGenerations; }; // playerInfo.c void playerInfo(); // boardInitialization.c char ** boardInitialization(); char ** boardCopyInitialization(); void freeBoard(char **gameBoard, char **arrayCopy, int height, int width); // generations.c void runGenerations(char ** gameBoard, char **arrayCopy, int height, int width, int numGenerations, struct Info *infoPtr); void checkIfAllInactive(char ** gameBoard, char **arrayCopy, int height, int width, struct Info *infoPtr); void endGame(char **gameBoard, char **arrayCopy, int height, int width, struct Info *infoPtr); // displayGenerations.c void displayGeneration(char ** gameBoard, char **arrayCopy, int height, int width); int countActiveNeighbors(char **arrayCopy, int height, int width, int rowIndex, int colIndex); // readPlayersInformation.c void readInGameFile(); void readPlayersInformation(struct Info *infoPtr); // displayGameSummary.c void writeToGameLog(); void displayGameSummary(struct Info *players);
C
#ifndef __INTEGER_TREE_H__ #define __INTEGER_TREE_H__ #include "base.h" #include "integer_list.h" // Represents a single tree node. typedef struct BTNode { int value; struct BTNode* left; // self-reference struct BTNode* right; // self-reference } BTNode; // Creates a tree node. BTNode* new_btnode(int value, BTNode* left, BTNode* right); // Creates a leaf node. BTNode* new_leaf(int value); // Prints the tree. void print_tree(BTNode* tree); // Prints tree followed by a line break. void println_tree(BTNode* tree); // Frees all nodes of the tree. void free_tree(BTNode* tree); // Computes the number of elements of the tree. int count_tree(BTNode* tree); // Computes the depth of the tree. int depth_tree(BTNode* tree); // Checks whether tree contains element. bool contains_tree(BTNode* tree, int x); // Removes all nodes containing value from the tree. // Does not respect any order in the tree! BTNode* remove_tree(BTNode* tree, int value); // Copies the tree. BTNode* copy_tree(BTNode* tree); // Checks whether two trees are equal. bool trees_equal(BTNode* t1, BTNode* t2); // Inserts value at the right position in the tree such that the following invariant holds. // For each node n its left subtree (if not empty) contains values smaller than n's value v // and its right subtree (if not empty) contains values equal to or larger than v. BTNode* insert_ordered_tree(BTNode* tree, int value); // Finds the first node in the ordered tree which contains the value x. BTNode* search_ordered_tree(BTNode* tree, int x); // Does an inorder traversal of the tree and prints each element. void print_inorder(BTNode* tree); // Does an inorder traversal of the tree and prints each element followed by a line break. void println_inorder(BTNode* tree); /////////////////////////////////////////////////////////////////////////// // Transforms element into something else. // typedef int (*MapFun)(int element, int x); // Maps the elements of the tree using f(element, x) and // returns a new tree with the same structure as the result. BTNode* map_tree(BTNode* tree, MapFun f, void* x); // Checks whether x satisfies a predicate. // typedef bool (*FilterFun)(int element, int x); // Filters the elements of the tree using pred(element, x) and // returns a list containing the result. Initially, result_list is NULL. Node* filter_tree(BTNode* tree, FilterFun pred, void* x, Node* result_list); // Filters and maps the elements of the tree using pred(element, x) and // f(element, x), resepectively. Returns a list containing the result. // Initially, result_list is NULL. Node* filter_map_tree(BTNode* tree, FilterFun pred, void* x, MapFun map, void* y, Node* result_list); // Aggregates a list: state is the intermediary aggregation result, element is the current element. // typedef int (*ReduceFun)(int state, int element); // Aggregates the values of the tree by sequentally applying state = f(state, element). int reduce_tree(BTNode* tree, ReduceFun f, int state); #endif
C
/* * ===================================================================================== * * Filename: cmd.h * * Description: * * Version: 1.0 * Created: 05/19/15 15:55:15 * Revision: none * Compiler: gcc * * Author: Chaos John (CJ), chaosjohn.yjh@gmail.com * Organization: * * ===================================================================================== */ #ifndef cmd_INC #define cmd_INC #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <malloc.h> #include "types.h" #include "fs.h" #include "utils.h" #include "permission.h" #include "mm.h" #include "jobs.h" /* * 执行指令 * */ int executeCmd(char *); /* * 打印help命令 * */ int printCmds(int, char **); /* * 退出 * */ int quit(int, char **); /* * 创建文件或修正文件时间 * */ int touch(int, char **); /* * 创建目录 * */ int mkdir(int, char **); /* * 列出当前目录的文件清单 * */ int ls(int, char **); /* * 按长格式列出当前目录的文件清单 * */ int ll(int, char **); /* * 更改文件的所有者 * */ int chowner(int, char **); /* * 更改文件的所属群组 * */ int chgroup(int, char **); /* * 新增群组 * */ int groupadd(int, char **); /* * 新增用户 * */ int useradd(int, char **); /* * 更新用户密码 * */ int passwd(int, char **); /* * 切换用户 * */ int su(int, char **); /* * 查看当前的用户 */ int whoami(int, char **); /* * 加入群组 * */ int joingroup(int, char **); /* * 显示指定用户的所有群组 * */ int showgroups(int, char **); /* * 显示所有用户 * */ int lsusers(int, char **); /* * 显示所有群组 * */ int lsgroups(int, char **); /* * 更改目录 * */ int cd(int, char **); /* * 使用首次适应算法分配内存 * */ int ffmalloc(int, char **); /* * 使用循环首次适应算法分配内存 * */ int nfmalloc(int, char **); /* * 使用最佳适应算法分配内存 * */ int bfmalloc(int, char **); /* * 使用最差适应算法分配内存 * */ int wfmalloc(int, char **); /* * 显示内存空闲表和内存分配表 * */ int showmm(int, char **); /* * 显示内存空闲表 * */ int showempty(int, char **); /* * 显示内存分配表 * */ int showused(int, char **); /* * 回收内存 * */ int freemm(int, char **); /* * 模拟多任务 * */ int runjobs(int, char **); #endif /* ----- #ifndef cmd_INC ----- */
C
#include<stdio.h> #include<stdlib.h> #include<limits.h> #include "def.h" #include "search.h" #include "helper.h" #include "insert_del.h" #include "print.h" #include "helper_main.h" ll_carrier *T,*H; double buffer = 0; void main() { double buffer; H = T = NULL; init_end(&H,&T); insert_end(H,H,0); int choice_main; int y_n; while(1) { printf("This main menu contains submenus\n"); printf("Choice of submenus:\n1.Internal data related functions\n2.Search functions\n3.Insertion related function\n4.Deletion\n5.Print The document\n6.Buffer Related functions\n7.Exit\n: "); scanf("%d",&choice_main); switch(choice_main) { case 1: data_related(&H,&T,&buffer); break; case 2: search(&H,&T,&buffer); break; case 3: insert(&H,&T); break; case 4: delete(&H,&T,&buffer); break; case 5: print_block(H); //print(&H,&T); break; case 6: buffer_functions(&H,&T,&buffer); break; case 7: printf("\nWould you like to save this SpreadSheet as .csv file 1/0: "); scanf("%d",&y_n); if(y_n) save(H); exit(0); default: printf("Menu not defined!\n"); } } }
C
#include<stdio.h> int main (void){ int c1, c2, hh, mm, x, y, s; double diff, ss; scanf("%d %d", &c1, &c2); diff = (c2 - c1) / 100.00; hh = diff / 3600; mm = (diff - hh * 3600) / 60; ss = diff - hh * 3600 - mm * 60.0; x = ss * 10; y = x % 10; if(y >= 5){ s = (x + 10) / 10; } printf("%d:%d:%d", hh, mm, s); return 0; }
C
#include <stdio.h> #include <limits.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <malloc.h> #include <errno.h> #include <ctype.h> #include <sys/stat.h> #include <libgen.h> #define countof(X) (sizeof(X) / sizeof(X[0])) #define TRUE 1 #define FALSE 0 int fexists(const char* path) { char buf[PATH_MAX]; struct stat info; realpath(path, &buf[0]); if (lstat(buf, &info) != 0) { if (errno == ENOENT || errno == EACCES) { return FALSE; } } return S_ISREG(info.st_mode) ? TRUE : FALSE; } int dexists(const char* path) { char buf[PATH_MAX]; struct stat info; realpath(path, &buf[0]); if (lstat(buf, &info) != 0) { if (errno == ENOENT || errno == EACCES) { return FALSE; } } return S_ISDIR(info.st_mode) ? TRUE : FALSE; } size_t fsize(FILE* fp) { fseek(fp, 0L, SEEK_END); size_t size = ftell(fp); fseek(fp, 0L, SEEK_SET); return size; } char* rstrip(char* s) { size_t len = strlen(s); for (int i = len - 1; i >= 0; i--) { if (!isspace(s[i])) break; s[i] = '\0'; } return s; } void xfree(void* lp) { if (lp != NULL) { free(lp); } } int strdump(const char* path, const char* value, int retry) { FILE* fp = fopen(path, "w"); size_t size = strlen(value); if (fp != NULL) { size_t nbytes = 0; do { nbytes += fwrite(value, 1, size - nbytes, fp); if (errno != 0) { break; } } while (retry == TRUE && nbytes < size); fclose(fp); } return errno; } int strload(const char* path, char** pbuf, int retry) { FILE* fp = fopen(path, "r"); if (fp != NULL) { size_t size = fsize(fp); size_t nbytes = 0; char* buf = malloc(size + 1); buf[size] = '\0'; do { nbytes += fread(buf + nbytes, 1, size - nbytes, fp); if (errno != 0) { free(buf); break; } } while (retry == TRUE && nbytes < size); *pbuf = buf; fclose(fp); } return errno; } const char* newid_path = "/sys/bus/pci/drivers/vfio-pci/new_id"; const char* remid_path = "/sys/bus/pci/drivers/vfio-pci/remove_id"; const char* probe_path = "/sys/bus/pci/drivers_probe"; const char* vfctl_path = "/etc/vfio/vfioctl.lst"; const char* driver_unbind_fmt = "/sys/bus/pci/devices/%s/driver/unbind"; const char* vfiodr_unbind_fmt = "/sys/bus/pci/drivers/vfio-pci/unbind"; const char* device_fmt = "/sys/bus/pci/devices/%s/%s"; char* vfctl_allowed[64]; int vfio_allowed(const char* dev) { for (int i = 0; i < (int) countof(vfctl_allowed) && vfctl_allowed[i] != NULL; i++) { if (strcmp(dev, vfctl_allowed[i]) == 0) return TRUE; } return FALSE; } int vfio_bind(const char* dev) { char* vendor = NULL; char* device = NULL; char buf[BUFSIZ]; if (vfio_allowed(dev) == FALSE) { return EPERM; } snprintf(buf, sizeof(buf), device_fmt, dev, "vendor"); if (strload(buf, &vendor, FALSE) != 0) goto _err; snprintf(buf, sizeof(buf), device_fmt, dev, "device"); if (strload(buf, &device, FALSE) != 0) goto _err; snprintf(buf, sizeof(buf), device_fmt, dev, "driver"); if (dexists(buf) == TRUE) { snprintf(buf, sizeof(buf), driver_unbind_fmt, dev); if (strdump(buf, dev, TRUE) != 0) goto _err; } snprintf(buf, sizeof(buf), "%s %s\n", rstrip(vendor), rstrip(device)); if (strdump(newid_path, buf, TRUE) != 0) goto _err; _err: xfree(device); xfree(vendor); return errno; } int vfio_unbind(const char* dev) { char* vendor = NULL; char* device = NULL; char buf[BUFSIZ]; if (vfio_allowed(dev) == FALSE) { return EPERM; } snprintf(buf, sizeof(buf), device_fmt, dev, "vendor"); if (strload(buf, &vendor, FALSE) != 0) goto _err; snprintf(buf, sizeof(buf), device_fmt, dev, "device"); if (strload(buf, &device, FALSE) != 0) goto _err; snprintf(buf, sizeof(buf), device_fmt, dev, "driver"); if (dexists(buf)) { snprintf(buf, sizeof(buf), vfiodr_unbind_fmt, dev); if (strdump(buf, dev, TRUE) != 0) goto _err; } snprintf(buf, sizeof(buf), "%s %s\n", rstrip(vendor), rstrip(device)); if (strdump(remid_path, buf, TRUE) != 0) goto _err; if (strdump(probe_path, dev, TRUE) != 0) goto _err; _err: xfree(device); xfree(vendor); return errno; } void do_bind(char** argv, int beg, int end) { for (int i = beg; i < end; i++) { printf("Binding [%s] -> %s\n", argv[i], strerror(vfio_bind(argv[i]))); } } void do_unbind(char** argv, int beg, int end) { for (int i = beg; i < end; i++) { printf("Unbinding [%s] -> %s\n", argv[i], strerror(vfio_unbind(argv[i]))); } } int load_vfctl(char** vfctl) { if (strload(vfctl_path, vfctl, TRUE) != 0) goto _err; vfctl_allowed[0] = strtok(*vfctl, " \r\n"); for (int i = 1; i < (int) countof(vfctl_allowed) && vfctl_allowed[i - 1] != NULL; i++) { vfctl_allowed[i] = strtok(NULL, " \r\n"); } _err: return errno; } void help(void) { puts("Usage:"); puts(" vfioctl command device-ids"); puts(" command :: bind, unbind"); } int main(int argc, char *argv[]) { setuid(geteuid()); setgid(getegid()); if (argc > 1) { char* base = basename(argv[0]); char* vfctl = NULL; if (load_vfctl(&vfctl) != 0) { puts("Failed loading vfioctl.lst"); return EXIT_FAILURE; } if (strcmp(base, "vfio-bind") == 0) { do_bind(argv, 1, argc); } else if (strcmp(base, "vfio-unbind") == 0) { do_unbind(argv, 1, argc); } else { if (strcmp(argv[1], "bind") == 0) { do_bind(argv, 2, argc); } else if (strcmp(argv[1], "unbind") == 0) { do_unbind(argv, 2, argc); } else { help(); } } xfree(vfctl); } else { help(); } return EXIT_SUCCESS; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* int_converter_helper_2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lmalaya <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/07/08 10:28:33 by lmalaya #+# #+# */ /* Updated: 2019/07/08 10:28:35 by lmalaya ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" int is_signed(t_spec *s) { return (ft_strchr("di", s->specifier) ? 1 : 0); } long long int get_signed_int(t_spec *s, va_list args) { if (s->length_modifier == H) return ((short int)va_arg(args, int)); if (s->length_modifier == HH) return ((char)va_arg(args, int)); if (s->length_modifier == L) return (va_arg(args, long int)); if (s->length_modifier == LL) return (va_arg(args, long long int)); return (va_arg(args, int)); } unsigned long long int get_unsigned_int(t_spec *s, va_list args) { if (s->length_modifier == H) return (unsigned short int)va_arg(args, int); if (s->length_modifier == HH) return (unsigned char)va_arg(args, int); if (s->length_modifier == L) return (va_arg(args, unsigned long int)); if (s->length_modifier == LL) return (va_arg(args, unsigned long long int)); return (va_arg(args, unsigned int)); } unsigned long long int get_int(t_spec *s, va_list args, char *sign) { long long int i; if (is_signed(s)) { i = get_signed_int(s, args); *sign = (i < 0) ? '-' : '+'; return ((unsigned long long int)(i < 0 ? -i : i)); } else { *sign = '+'; return (get_unsigned_int(s, args)); } }
C
/* * graph_builder.c */ #include "graph_builder.h" #include "linked_list.h" #include "vertex.h" #include "edge.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #define STATION 0 #define TIME 1 // This might be handy for you when sorting int comparator(const void* a, const void* b) { const vertex** vertexA = (const vertex**) a; const vertex** vertexB = (const vertex**) b; // printf("%s, %s\n", (*vertexA)->name, (*vertexB)->name); int result = strncmp((*vertexA)->name, (*vertexB)->name, 100); if (!result) { result = (*vertexA)->time - (*vertexB) ->time; } return result; } int minutesaftermidnight(char time[5]); void add_internal_edges(int departurecounter, vertex** vertices) { int i; for (i = 0; i < departurecounter; i++) { vertex* v = vertices[i]; int j; for (j = i; j < departurecounter; j++) { if ((strcmp(v->name, vertices[j]->name) == 0) && ((vertices[j]->time - v->time) >= 5)) { add_edge_to_vertex(v, (vertices[j]->time - v->time), 1, vertices[j]); } } } } graph *build_graph(char *filename) { int c, l, departurecounter, state, namecounter, aftermidnight, lasttime; int has_last = 0; linked_list *departures = init_linked_list(); graph *graph; char time[] = "00:00"; char stationName[30]; vertex** vertices; FILE* file = fopen(filename, "r"); char line[256]; namecounter = 0; aftermidnight = 0; l = 0; departurecounter = 0; lasttime = 0; while (fgets(line, 256, file) != 0) { l = 0; state = STATION; while ((c = line[l]) != '\0') { //printf("LINE: %s\n", line); //fflush(stdout); if (c == ' ' || c == '\t') { //Whitespace, do nothing } else if (c == ',') { // printf("Found , \n"); // fflush(stdout); state = TIME; stationName[namecounter] = '\0'; departurecounter++; namecounter = 0; } else if (c == '\n') { // printf("Found newline, \n"); // fflush(stdout); if (state == STATION) { aftermidnight = 0; lasttime = 0; has_last = 0; } else if (state == TIME) { state = STATION; } } else { // printf("Found character \n"); // fflush(stdout); if (state == STATION) { stationName[namecounter] = c; namecounter++; } else if (state == TIME) { // printf("Doing time \n"); // fflush(stdout); int i; int min; vertex* v; for (i = 0; i < 5; i++) { time[i] = c; l++; c = line[l]; } min = minutesaftermidnight(time); if (aftermidnight) { min += 2440; } else if ((lasttime != 0) && (min < lasttime)) { min += 2440; aftermidnight = 1; } //Make vertex // printf("station name length:%d\n", strlen(stationName)); // fflush(stdout); v = malloc(sizeof(vertex)); v->name = malloc(strlen(stationName) + 1); memset(v->name, '\0', strlen(stationName) + 1); strcpy(v->name, stationName); printf("station name:%s\n", v->name); fflush(stdout); v->time = min; v->key = 0; v->trainshifts = 0; v->edges = init_linked_list(); //Add externeal edge to previous station if (has_last != 0) { printf("Add new edge\n"); // add_edge_to_vertex(v, (min - lasttime), 0, // departures->next->data); add_edge_to_vertex(departures->next->data, (min - lasttime), 0, v); } //Add to departures add_element(departures, v); lasttime = min; has_last = 1; // printf("BReaking bad\n"); // fflush(stdout); break; } } l++; } } //Add all vertices to a list of vertex pointers vertices = malloc(sizeof(vertex*) * departurecounter); // printf("departures %d\n", departurecounter); // fflush(stdout); int i; linked_list* current = departures->next; for (i = 0; i < departurecounter; i++) { vertices[i] = (vertex*) (current->data); // printf("%d name: %s, id %d\n", i, vertices[i]->name, vertices[i]); // fflush(stdout); current = current->next; } printf("sorting\n"); fflush(stdout); qsort(vertices, departurecounter, sizeof(vertex*), comparator); printf("sorted\n"); fflush(stdout); //Add internal edges; add_internal_edges(departurecounter, vertices); graph = malloc(sizeof(struct graph)); graph->vertices = vertices; graph->number_vertices = departurecounter; return graph; } int minutesaftermidnight(char time[5]) { int i = 0; i = (time[4] - '0'); i += ((time[3] - '0') * 10); i += ((time[1] - '0') * 60); i += ((time[0] - '0') * 600); return i; }
C
/* * SPI.c * * Created on: 01.10.2020 * Author: Piotr */ #include "SPI.h" #if BME280_SPI void SPI_Conf(void); void SELECT (void); void DESELECT (void); #endif #if BME280_SPI /****************************************************************************/ /* Configuration of SPI protocol */ /****************************************************************************/ void SPI_Conf(void) { GPIO_InitTypeDef GPIO_InitStructure; SPI_InitTypeDef SPI_InitStructure; // Run clocks for peripherals RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOA | RCC_APB2Periph_SPI1 | RCC_APB2Periph_AFIO, ENABLE); // PA0 as CS GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_Init(GPIOA, &GPIO_InitStructure); //SCK -> PA5, MISO -> PA6, MOSI -> PA7 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_Init(GPIOA, &GPIO_InitStructure); // Configuration SPI SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex; SPI_InitStructure.SPI_Mode = SPI_Mode_Master; SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b; SPI_InitStructure.SPI_CPOL = SPI_CPOL_High; SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge; SPI_InitStructure.SPI_NSS = SPI_NSS_Soft; SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_8; SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; SPI_InitStructure.SPI_CRCPolynomial = 7; SPI_Init(SPI1, &SPI_InitStructure); // Turn on SPI SPI_Cmd(SPI1, ENABLE); SELECT(); DESELECT(); } #endif /****************************************************************************/ /* Select slave */ /****************************************************************************/ #if BME280_SPI void SELECT (void) // CS in low state { GPIO_ResetBits(GPIOA, GPIO_Pin_0); } #endif /****************************************************************************/ /* Deelect slave */ /****************************************************************************/ #if BME280_SPI void DESELECT (void) // CS in high state { GPIO_SetBits(GPIOA, GPIO_Pin_0); } #endif /****************************************************************************/ /* Send a few data by SPI */ /****************************************************************************/ #if BME280_SPI void SPI_SendData (uint8_t address, uint8_t *Data, uint8_t size) { const uint8_t register_mask = 0x7F; uint8_t data; SELECT(); for (uint8_t i = 0; i < size; i++) { data = Data[i]; while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE) == RESET); SPI_I2S_SendData(SPI1, register_mask & address); while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE) == RESET); SPI_I2S_SendData(SPI1, data); address++; } while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE) == RESET); DESELECT(); } #endif /****************************************************************************/ /* Receiving a few data from external device by SPI */ /****************************************************************************/ #if BME280_SPI void SPI_ReceiveData (uint8_t address, uint8_t *Data, uint8_t size) { SELECT(); while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE) == RESET); SPI_I2S_SendData(SPI1, address); while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET); SPI_I2S_ReceiveData(SPI1); for (uint8_t i = 0; i < size; i++) { while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_TXE) == RESET); SPI_I2S_SendData(SPI1, 0); while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET); Data[i] = SPI_I2S_ReceiveData(SPI1); } DESELECT(); } #endif
C
/* LGPL (v2.1 or any later version) - see LICENSE file for details */ #include <ccan/timer/timer.h> #include <ccan/array_size/array_size.h> #include <ccan/ilog/ilog.h> #include <ccan/likely/likely.h> #include <stdlib.h> #include <stdio.h> #define PER_LEVEL (1ULL << TIMER_LEVEL_BITS) struct timer_level { struct list_head list[PER_LEVEL]; }; static uint64_t time_to_grains(struct timemono t) { return t.ts.tv_sec * ((uint64_t)1000000000 / TIMER_GRANULARITY) + (t.ts.tv_nsec / TIMER_GRANULARITY); } static struct timemono grains_to_time(uint64_t grains) { struct timemono t; t.ts.tv_sec = grains / (1000000000 / TIMER_GRANULARITY); t.ts.tv_nsec = (grains % (1000000000 / TIMER_GRANULARITY)) * TIMER_GRANULARITY; return t; } void timers_init(struct timers *timers, struct timemono start) { unsigned int i; list_head_init(&timers->far); timers->base = time_to_grains(start); timers->first = -1ULL; memset(timers->firsts, 0xFF, sizeof(timers->firsts)); for (i = 0; i < ARRAY_SIZE(timers->level); i++) timers->level[i] = NULL; } static unsigned int level_of(const struct timers *timers, uint64_t time) { uint64_t diff; /* Level depends how far away it is. */ diff = time - timers->base; return ilog64(diff / 2) / TIMER_LEVEL_BITS; } static void timer_add_raw(struct timers *timers, struct timer *t) { struct list_head *l; unsigned int level = level_of(timers, t->time); uint64_t *first; if (!timers->level[level]) { l = &timers->far; first = &timers->firsts[ARRAY_SIZE(timers->level)]; } else { int off = (t->time >> (level*TIMER_LEVEL_BITS)) & (PER_LEVEL-1); l = &timers->level[level]->list[off]; first = &timers->firsts[level]; } list_add_tail(l, &t->list); if (t->time < *first) *first = t->time; } void timer_init(struct timer *t) { list_node_init(&t->list); } static bool list_node_initted(const struct list_node *n) { return n->prev == n; } void timer_addrel(struct timers *timers, struct timer *t, struct timerel rel) { assert(list_node_initted(&t->list)); t->time = time_to_grains(timemono_add(time_mono(), rel)); #if TIME_HAVE_MONOTONIC assert(t->time >= timers->base); #else /* Added in the past? Treat it as imminent. */ if (t->time < timers->base) t->time = timers->base; #endif if (t->time < timers->first) timers->first = t->time; timer_add_raw(timers, t); } void timer_addmono(struct timers *timers, struct timer *t, struct timemono when) { assert(list_node_initted(&t->list)); t->time = time_to_grains(when); /* Added in the past? Treat it as imminent. */ if (t->time < timers->base) t->time = timers->base; if (t->time < timers->first) timers->first = t->time; timer_add_raw(timers, t); } /* FIXME: inline */ void timer_del(struct timers *timers UNNEEDED, struct timer *t) { list_del_init(&t->list); } static void timers_far_get(struct timers *timers, struct list_head *list, uint64_t when) { struct timer *i, *next; list_for_each_safe(&timers->far, i, next, list) { if (i->time <= when) { list_del_from(&timers->far, &i->list); list_add_tail(list, &i->list); } } } static void add_level(struct timers *timers, unsigned int level) { struct timer_level *l; struct timer *t; unsigned int i; struct list_head from_far; l = malloc(sizeof(*l)); if (!l) return; for (i = 0; i < ARRAY_SIZE(l->list); i++) list_head_init(&l->list[i]); timers->level[level] = l; list_head_init(&from_far); timers_far_get(timers, &from_far, timers->base + (1ULL << ((level+1)*TIMER_LEVEL_BITS)) - 1); while ((t = list_pop(&from_far, struct timer, list)) != NULL) timer_add_raw(timers, t); } /* We don't need to search past the first at level 0, since the * bucket range is 1; they're all the same. */ static const struct timer *find_first(const struct list_head *list, unsigned int level, const struct timer *prev) { struct timer *t; list_for_each(list, t, list) { if (!prev || t->time < prev->time) prev = t; if (level == 0) break; } return prev; } /* Update level's first watermark, and return overall first. */ static const struct timer *first_for_level(struct timers *timers, size_t level, const struct timer *level_first, const struct timer *first) { if (level_first) { timers->firsts[level] = level_first->time; if (!first || level_first->time < first->time) first = level_first; } else { timers->firsts[level] = -1ULL; } return first; } static bool level_may_beat(const struct timers *timers, size_t level, const struct timer *first) { return !first || timers->firsts[level] < first->time; } /* FIXME: Suboptimal */ static const struct timer *brute_force_first(struct timers *timers) { unsigned int l, i; const struct timer *found = NULL; for (l = 0; l < ARRAY_SIZE(timers->level) && timers->level[l]; l++) { const struct timer *t = NULL; /* Do we know they don't have a better one? */ if (!level_may_beat(timers, l, found)) continue; /* Find first timer on this level. */ for (i = 0; i < PER_LEVEL; i++) t = find_first(&timers->level[l]->list[i], l, t); found = first_for_level(timers, l, t, found); } /* Check (and update) far list if there's a chance. */ l = ARRAY_SIZE(timers->level); if (level_may_beat(timers, l, found)) { const struct timer *t = find_first(&timers->far, l, NULL); found = first_for_level(timers, l, t, found); } return found; } static const struct timer *get_first(struct timers *timers) { /* We can have just far timers, for example. */ if (timers->level[0]) { /* First search rest of lower buckets; we've already spilled * so if we find one there we don't need to search further. */ unsigned int i, off = timers->base % PER_LEVEL; for (i = off; i < PER_LEVEL; i++) { struct list_head *h = &timers->level[0]->list[i]; if (!list_empty(h)) return find_first(h, 0, NULL); } } /* From here on, we're searching non-normalized parts of the * data structure, which is much subtler. * * So we brute force. */ return brute_force_first(timers); } static bool update_first(struct timers *timers) { const struct timer *found = get_first(timers); if (!found) { timers->first = -1ULL; return false; } timers->first = found->time; return true; } bool timer_earliest(struct timers *timers, struct timemono *first) { if (!update_first(timers)) return false; *first = grains_to_time(timers->first); return true; } /* Assume no timers before 'time', cascade down and update base time. */ static void timer_fast_forward(struct timers *timers, uint64_t time) { unsigned int level, changed; int need_level = -1; struct list_head list; struct timer *i; /* How many bits changed between base and time? * Each time we wrap, we need to empty buckets from above. */ if (time == timers->base) return; changed = ilog64_nz(time ^ timers->base); level = (changed - 1) / TIMER_LEVEL_BITS; /* Buckets always empty downwards, so we could cascade manually, * but it's rarely very many so we just remove and re-add */ list_head_init(&list); do { if (!timers->level[level]) { /* We need any which belong on this level. */ timers_far_get(timers, &list, timers->base + (1ULL << ((level+1)*TIMER_LEVEL_BITS))-1); need_level = level; } else { unsigned src; /* Get all timers from this bucket. */ src = (time >> (level * TIMER_LEVEL_BITS)) % PER_LEVEL; list_append_list(&list, &timers->level[level]->list[src]); } } while (level--); /* Did we hit the last level? If so, add. */ if (need_level != -1) add_level(timers, need_level); /* Fast-forward the time, and re-add everyone. */ timers->base = time; while ((i = list_pop(&list, struct timer, list)) != NULL) timer_add_raw(timers, i); } /* Returns an expired timer. */ struct timer *timers_expire(struct timers *timers, struct timemono expire) { uint64_t now = time_to_grains(expire); unsigned int off; struct timer *t; assert(now >= timers->base); if (!timers->level[0]) { if (list_empty(&timers->far)) return NULL; add_level(timers, 0); } do { if (timers->first > now) { timer_fast_forward(timers, now); return NULL; } timer_fast_forward(timers, timers->first); off = timers->base % PER_LEVEL; /* This *may* be NULL, if we deleted the first timer */ t = list_pop(&timers->level[0]->list[off], struct timer, list); if (t) list_node_init(&t->list); } while (!t && update_first(timers)); return t; } static bool timer_list_check(const struct list_head *l, uint64_t min, uint64_t max, uint64_t first, const char *abortstr) { const struct timer *t; if (!list_check(l, abortstr)) return false; list_for_each(l, t, list) { if (t->time < min || t->time > max) { if (abortstr) { fprintf(stderr, "%s: timer %p %llu not %llu-%llu\n", abortstr, t, (long long)t->time, (long long)min, (long long)max); abort(); } return false; } if (t->time < first) { if (abortstr) { fprintf(stderr, "%s: timer %p %llu < minimum %llu\n", abortstr, t, (long long)t->time, (long long)first); abort(); } return false; } } return true; } struct timers *timers_check(const struct timers *timers, const char *abortstr) { unsigned int l, i, off; uint64_t base; l = 0; if (!timers->level[0]) goto past_levels; /* First level is simple. */ off = timers->base % PER_LEVEL; for (i = 0; i < PER_LEVEL; i++) { struct list_head *h; h = &timers->level[l]->list[(i+off) % PER_LEVEL]; if (!timer_list_check(h, timers->base + i, timers->base + i, timers->firsts[l], abortstr)) return NULL; } /* For other levels, "current" bucket has been emptied, and may contain * entries for the current + level_size bucket. */ for (l = 1; l < ARRAY_SIZE(timers->level) && timers->level[l]; l++) { uint64_t per_bucket = 1ULL << (TIMER_LEVEL_BITS * l); off = ((timers->base >> (l*TIMER_LEVEL_BITS)) % PER_LEVEL); /* We start at *next* bucket. */ base = (timers->base & ~(per_bucket - 1)) + per_bucket; for (i = 1; i <= PER_LEVEL; i++) { struct list_head *h; h = &timers->level[l]->list[(i+off) % PER_LEVEL]; if (!timer_list_check(h, base, base + per_bucket - 1, timers->firsts[l], abortstr)) return NULL; base += per_bucket; } } past_levels: base = (timers->base & ~((1ULL << (TIMER_LEVEL_BITS * l)) - 1)) + (1ULL << (TIMER_LEVEL_BITS * l)) - 1; if (!timer_list_check(&timers->far, base, -1ULL, timers->firsts[ARRAY_SIZE(timers->level)], abortstr)) return NULL; return (struct timers *)timers; } #ifdef CCAN_TIMER_DEBUG static void dump_bucket_stats(FILE *fp, const struct list_head *h) { unsigned long long min, max, num; struct timer *t; if (list_empty(h)) { printf("\n"); return; } min = -1ULL; max = 0; num = 0; list_for_each(h, t, list) { if (t->time < min) min = t->time; if (t->time > max) max = t->time; num++; } fprintf(fp, " %llu (%llu-%llu)\n", num, min, max); } void timers_dump(const struct timers *timers, FILE *fp) { unsigned int l, i, off; unsigned long long base; if (!fp) fp = stderr; fprintf(fp, "Base: %llu\n", (unsigned long long)timers->base); if (!timers->level[0]) goto past_levels; fprintf(fp, "Level 0:\n"); /* First level is simple. */ off = timers->base % PER_LEVEL; for (i = 0; i < PER_LEVEL; i++) { const struct list_head *h; fprintf(fp, " Bucket %llu (%lu):", (i+off) % PER_LEVEL, timers->base + i); h = &timers->level[0]->list[(i+off) % PER_LEVEL]; dump_bucket_stats(fp, h); } /* For other levels, "current" bucket has been emptied, and may contain * entries for the current + level_size bucket. */ for (l = 1; l < ARRAY_SIZE(timers->level) && timers->level[l]; l++) { uint64_t per_bucket = 1ULL << (TIMER_LEVEL_BITS * l); off = ((timers->base >> (l*TIMER_LEVEL_BITS)) % PER_LEVEL); /* We start at *next* bucket. */ base = (timers->base & ~(per_bucket - 1)) + per_bucket; fprintf(fp, "Level %u:\n", l); for (i = 1; i <= PER_LEVEL; i++) { const struct list_head *h; fprintf(fp, " Bucket %llu (%llu - %llu):", (i+off) % PER_LEVEL, base, base + per_bucket - 1); h = &timers->level[l]->list[(i+off) % PER_LEVEL]; dump_bucket_stats(fp, h); base += per_bucket; } } past_levels: if (!list_empty(&timers->far)) { fprintf(fp, "Far timers:"); dump_bucket_stats(fp, &timers->far); } } #endif void timers_cleanup(struct timers *timers) { unsigned int l; for (l = 0; l < ARRAY_SIZE(timers->level); l++) free(timers->level[l]); }
C
/* ** EPITECH PROJECT, 2021 ** checker ** File description: ** check victory or defeat */ #include "../include/my.h" int check_victory(char **map) { for (int y = 0; map[y] != 0; y++) for (int x = 0; map[y][x] != '\0'; x++) if (map[y][x] == 'O') return (0); return (1); } int check_defeat(char **map) { for (int y = 0; map[y] != 0; y++) for (int x = 0; map[y][x] != '\0'; x++) if (map[y][x] == 'X' && ((map[y][x-1] == '#' && map[y+1][x] == '#') || (map[y][x+1] == '#' && map[y+1][x] == '#') || (map[y][x-1] == '#' && map[y-1][x] == '#') || (map[y][x+1] == '#' && map[y-1][x] == '#'))) return (1); return (0); }
C
#include<stdio.h> #include<string.h> char str[100000][51]; int n; int isSmall(char *str1, char *str2){ int len1 = strlen(str1); int len2 = strlen(str2); if(str1[0] == '-' && str2[0] != '-') return 1; if(str1[0] != '-' && str2[0] == '-') return 0; if(str1[0] != '-' && str2[0] != '-'){ if(len1>len2) return 0; if(len2>len1) return 1; if(strcmp(str1, str2)>0) return 0; else return 1; } else{ if(len1>len2) return 1; if(len2>len1) return 0; if(strcmp(str1, str2)>0) return 1; else return 0; } } void sort(){ for(int i=0; i<n; i++){ for(int j=i+1; j<n; j++){ if(isSmall(str[i], str[j])){ char temp[51]; strcpy(temp, str[i]); strcpy(str[i], str[j]); strcpy(str[j], temp); } } } } int main(){ scanf("%d", &n); for(int i=0; i<n; i++){ scanf("%s", str[i]); } sort(); for(int i=0; i<n; i++){ printf("%s\n", str[i]); } }
C
/* * 15 - Know your architecture */ #include <stdio.h> int main() { const char ids[6][15] = { "char", "int", "long", "l long", "float", "double" }; unsigned long sizes[] = { sizeof(char), sizeof(int), sizeof(long), sizeof(long long), sizeof(float), sizeof(double) }; printf("Size:\t\tbytes \tbits\n"); printf("---------------------------\n"); for (int i = 0; i < sizeof(sizes) / sizeof(sizes[0]); i++) { printf("%s\t\t%lu\t%lu\n", ids[i], sizes[i], 8 * sizes[i]); } return 0; }
C
#include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #define pint pid_t #include <sys/wait.h> int main(){ pint t; t = fork(); int t1 = 0; if(t == -1){ printf("Error.\n"); exit(0); } else if(t == 0){ int p1 = getpid(); int p2 = getppid(); printf("Child: %d \n Parent: %d\n",p1,p2); exit(0); } else{ wait(&t1); int p1 = getpid(); int p2 = getppid(); printf("Child: %d \n Parent: %d\n",p1,p2); exit(0); } printf("Done.\n"); }
C
#include <stdio.h> int main(){ int count[42] = {0}; int i, input, r; for(i = 0; i < 10; i++){ scanf("%d", &input); r = input % 42; count[r] += 1; } int result = 0; for(i = 0; i < 42; i++){ if(count[i] > 0){ result += 1; } } printf("%d\n", result); return 0; }
C
#include<stdio.h> int main() { float base, height; printf("Digite e confirme a altura e depois a base\n"); scanf("%f %f", &height, &base); printf("Sua área é de: %.2f\n", ((height*base)/2)); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* handle_float.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: vbastion <vbastion@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/08/08 14:34:19 by vbastion #+# #+# */ /* Updated: 2018/03/25 18:09:46 by vbastion ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" static int handle_flo_pre(char *buf, size_t *len, t_flag *flag, double f) { size_t pre; int tmp_i; buf[(*len)] = '.'; (*len)++; pre = (flag->sz_flag & 6) ? flag->pre : 6; f += rounder(pre + 1); while (pre != 0) { if (f == 0) { buf[(*len)++] = '0'; pre--; continue ; } f *= 10; tmp_i = (int)(f); f -= tmp_i; pre--; buf[(*len)] = '0' + tmp_i; (*len)++; } return (1); } static int print_float(char *buf, size_t len, t_flag *flag) { u_char spec; spec = (((flag->flag & (1 << 10)) == 0) | (((flag->sz_flag & 1) && flag->min > len) << 1)); if (spec == 3) fpf_buf_addfillers((flag->flag & (1 << 9)) == 0, flag->min - len); fpf_buf_add(buf, len); if (spec == 2) fpf_buf_addfillers(1, flag->min - len); return (1); } int fpf_handle_flo(va_list *ap, t_flag *flag) { char *buf; long long real; double f; size_t len; u_char neg; buf = fpf_buf_get()->tmp_buf; ft_bzero(buf, FT_TMPBSZ); f = va_arg(*ap, double); neg = f < 0; if (neg) { f = -f; buf[0] = '-'; } len = neg; real = (long long)f; ft_ltobuf(real, 10, 0, buf + len); len = fpf_strlen(buf); f -= real; if (((flag->sz_flag & 6) && flag->pre != 0) || ((flag->sz_flag & 6) == 0)) handle_flo_pre(buf, &len, flag, f); return (print_float(buf, len, flag)); }
C
#include<stdio.h> #include<conio.h> #include<malloc.h> struct node { int data; struct node* next; }; typedef struct node NODE; typedef struct node* PNODE; typedef struct node** PPNODE; void InsertFirst(PPNODE,int); void display(PNODE); void InsertLast(PPNODE,int); void DeleteFirst(PPNODE); void DeleteLast(PPNODE); int main() { PNODE Head=NULL; InsertFirst(&Head,101); InsertFirst(&Head,51); InsertFirst(&Head,21); InsertFirst(&Head,11); display(Head); InsertLast(&Head,201); display(Head); InsertLast(&Head,251); display(Head); DeleteFirst(&Head); display(Head); DeleteLast(&Head); display(Head); InsertLast(&Head,300); display(Head); return 0; } void InsertFirst(PPNODE first,int no) { PNODE newn=NULL; newn=(PNODE)malloc(sizeof(NODE)); newn->data=no; newn->next=NULL; if(*first==NULL) { *first=newn; } else { newn->next=*first; *first=newn; } printf("%d is Added : At First \n",newn->data); } void display(PNODE first) { printf("\n+---------------------------------------------+\n"); printf("|\tLinked List\t\t\t |"); printf("\n+---------------------------------------------+\n|"); if(first==NULL) { printf("\nLink List Is Empty"); } while(first!=NULL) { printf("%d\t",first->data); first=first->next; } printf("\n+---------------------------------------------+\n"); printf("\n"); } void InsertLast(PPNODE first,int no) { PNODE newn=(PNODE)malloc(sizeof(NODE)); newn->data=no; newn->next=NULL; PNODE temp=*first; if(*first==NULL) { *first=newn; } else { while(temp->next!=NULL) { temp=temp->next; } temp->next=newn; } printf("%d is Inserted at Last Position \n",newn->data); } void DeleteFirst(PPNODE first) { PNODE temp=*first; (*first)=temp->next; printf("\n%d is Removed : First Node Deleted\n",temp->data); free(temp); } void DeleteLast(PPNODE first) { PNODE temp=*first; while(temp->next->next!=NULL) { temp=temp->next; } printf("\n%d is Removed : One Node Deleted\n",(temp->next)->data); free(temp->next); temp->next=NULL; }
C
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #include <pthread.h> #include <semaphore.h> #include <unistd.h> #include <time.h> #define NAME_SIZE 100 #define BUFFER_SIZE 256 #define NUMBER_OF_CONFIGS 15 #define NUM_MAX_PESSOAS 20 int postos[]; //TRINCOS pthread_mutex_t mutex_utente; pthread_mutex_t mutex_posto_testagem; //trinco para ponto testagem pthread_mutex_t mutex_isolamento; //trinco para isolamento //SEMAFOROS sem_t fila_prio; sem_t fila_normal; sem_t fila_isolamento_prio; sem_t fila_isolamento_normal; //Variaveis globais int id_utentes = 0; //é o counter e o id do utente int numUtentesIsolamento = 0; int numUtentesInternamento = 0; int numUtentesPontoTestagem = 0; int numUtentesCentroTestagem = 0; int numUtentesFilaNormal = 0; int numUtentesFilaPriori = 0; int tempo_universal = 0; int iniciado = 0; typedef struct { int TEMPO_MEDIO_CHEGADA_UTENTES; int NUMERO_POSTOS_TESTAGEM; int NUMERO_CENTROS_TESTAGEM; int NUMERO_MAX_TESTES_PESSOA; int MAX_PESSOAS_FILA; int MAX_PESSOS_FILA_PRIORITARIA; int PROB_UTENTE_TER_COVID; int PROB_UTENTE_SER_PRIO; int ATUALIZACAO_RESULTADO; int NUMERO_MAX_DOENTES_INTERNAMENTO; int NUMERO_MAX_ISOLAMENTO; int TEMPO_ATENDIMENTO; int TEMPO_ISOLAMENTO; int TEMPO_TESTE_RAPIDO; int TEMPO_TESTE_CONVENCIONAL; }configuracao; configuracao config; struct utente { int id; int prioridade; //prioridade = 1 então é prioritario //se alguma destas está a 1 é o lugar onde se encontra o utente int posto_testagem; int sala_isolamento; int internamento; int saiu; int tipo_teste; int tempo; int covid; }; struct utente utentes[NUM_MAX_PESSOAS]; void adiciona_utente(int id, int prioridade, int posto_testagem, int sala_isolamento, int internamento, int saiu, int tipo_teste, int tempo, int covid) { int i = 0; while (utentes[i].id != NULL && i<NUM_MAX_PESSOAS) { i++; } if (utentes[i].id == NULL) { utentes[i].id = id; utentes[i].prioridade = prioridade; utentes[i].posto_testagem = posto_testagem; utentes[i].sala_isolamento = sala_isolamento; utentes[i].internamento = internamento; utentes[i].saiu = saiu; utentes[i].tipo_teste = tipo_teste; utentes[i].tempo = tempo; utentes[i].covid = covid; } } void imprime_utentes() { printf("----Utentes----\n"); int j; for (j = 0; j < NUM_MAX_PESSOAS; ++j) { if(utentes[j].id == NULL){ break; } printf("ID: %d ", utentes[j].id); printf("Prioridade: %d ", utentes[j].prioridade); printf("Posto: %d ", utentes[j].posto_testagem); printf("Sala: %d ", utentes[j].sala_isolamento); printf("Internamento: %d ", utentes[j].internamento); printf("Saiu: %d ", utentes[j].saiu); printf("Teste: %d ", utentes[j].tipo_teste); printf("Tempo: %d ", utentes[j].tempo); printf("Covid: %d ", utentes[j].covid); printf("\n"); } printf("--------\n\n"); } int random_num(int min, int max){ return (rand() % max) + min; } int* load_conf_simulador(char *file) { int* conf = (int*)malloc(sizeof(int) * NUMBER_OF_CONFIGS); FILE *fp = fopen(file, "rb"); if (fp == NULL) { printf("Não e possível abrir o ficheiro de configuração.\n"); abort(); } int num, i = 0; char name[NAME_SIZE], buff[BUFFER_SIZE]; while (fgets(buff, sizeof buff, fp) != NULL) { if (sscanf(buff, "%[^=]=%d", name, &num) == 2) conf[i++] = num; } fclose(fp); return conf; } //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX void *gerar_utentes(void *arg){ int probabilidade; char buffer[BUFFER_SIZE]; pthread_mutex_lock(&mutex_utente); int id_pessoal = id_utentes; id_utentes++; //adiciona na variavel global de utentes pthread_mutex_unlock(&mutex_utente); //DEFINIR PRIORIDADE int prioridade = 0; //printf("Prob de ser priori: %d \n",config.PROB_UTENTE_SER_PRIO); probabilidade = random_num(0,100); //printf("Prob que calhou: %d \n",probabilidade); if(probabilidade <= config.PROB_UTENTE_SER_PRIO){ prioridade = 1; } //DEFINIR TIPO DE TESTE 50/50 int tipo_teste = 0; //printf("Prob de ser teste longo: 50/50 \n"); probabilidade = random_num(1,2); //printf("Prob que calhou: %d \n",probabilidade); if(probabilidade == 1){ tipo_teste = 1; } //FILAS int saiu = 0; pthread_mutex_lock(&mutex_utente); if(prioridade == 0){ //verificar se tem espaço na fila if(numUtentesFilaNormal<config.MAX_PESSOAS_FILA){ numUtentesFilaNormal++; } else{ printf("Utente %d saiu por fila normal cheia \n", id_pessoal); saiu = 1; } } else{ //tem espaço na fila para criar uma pessoa prioritária if(numUtentesFilaPriori<config.MAX_PESSOS_FILA_PRIORITARIA){ numUtentesFilaPriori++; } else{ printf("Utente %d saiu por fila prioritaria cheia \n",id_pessoal); saiu = 1; } } pthread_mutex_unlock(&mutex_utente); //TEMPOS int tempo = tempo_universal; int tempo_no_centro = 0; int tempo_no_posto_de_testagem = 0; //tempo que demora no teste //COVID int covid = 0; //POSTO QUE FICOU int posto_pessoal = 0; adiciona_utente(id_pessoal, prioridade, NULL, NULL, NULL, saiu, tipo_teste, tempo, covid); //Simulação de entrar no centro while(1){ while(tempo_universal == utentes[id_pessoal].tempo){ //ZAWARUDOO Enquanto o tempo universal nao muda, nao faz nada. } //Time has begun to move again pthread_mutex_lock(&mutex_utente); tempo_no_centro++; pthread_mutex_unlock(&mutex_utente); utentes[id_pessoal].tempo = tempo_universal; //printf("Tempo do utente %d é %d \n",id_pessoal,tempo); //printf("Tempo universal é %d \n",tempo_universal); //printf("Tempo do utente %d no centro é %d \n \n",id_pessoal,tempo_no_centro); if(utentes[id_pessoal].saiu != 1){ //Se essa pessoa nao saiu if(utentes[id_pessoal].prioridade == 1){ //Se essa pessoa tem prioridade if(utentes[id_pessoal].posto_testagem == 2){ //Se essa pessoa já teve no posto de testagem printf("Utente %d já teve no posto de testagem e vai para o isolamento \n",id_pessoal); if(utentes[id_pessoal].sala_isolamento == 1){ //Se está no isolamento if(utentes[id_pessoal].internamento == 1){ //Se está no internamento } else{ //Se está não está no internamento } } else{ //Não está no isolamento } } if(utentes[id_pessoal].posto_testagem == 1){ //Está no ponto de testagem ------------------------------ printf("Utente %d está no ponto de testagem \n",id_pessoal); //verificar teste do utilizador if(utentes[id_pessoal].tipo_teste == 0){ //utente faz teste convencional if(tempo_no_posto_de_testagem < config.TEMPO_TESTE_CONVENCIONAL){ //espera para fazer o teste convencional pthread_mutex_lock(&mutex_utente); tempo_no_posto_de_testagem++; pthread_mutex_unlock(&mutex_utente); } else{ printf("O utente %d recebeu o resultado do teste convecional \n",id_pessoal); int random_covid; random_covid = random_num(0,100); //probabilidade de ter covid positivo if(random_covid <= config.PROB_UTENTE_TER_COVID){ utentes[id_pessoal].covid= 1; printf("O utente %d tem covid positivo \n \n",id_pessoal); } else{ printf("O utente %d nao tem covid \n", id_pessoal); postos[posto_pessoal] = 0; //posto fica livre utentes[id_pessoal].saiu = 1; //sai do centro } } } else{ //utente faz teste_rápido if(tempo_no_posto_de_testagem < config.TEMPO_TESTE_RAPIDO){ //espera para fazer o teste rápido pthread_mutex_lock(&mutex_utente); tempo_no_posto_de_testagem++; pthread_mutex_unlock(&mutex_utente); } else{ printf("O utente %d recebeu o resultado do teste rápido \n",id_pessoal); int random_covid; random_covid = random_num(0,100); //probabilidade de ter covid positivo if(random_covid <= config.PROB_UTENTE_TER_COVID){ utentes[id_pessoal].covid= 1; printf("O utente %d tem covid positivo \n \n",id_pessoal); } else{ printf("O utente %d nao tem covid \n", id_pessoal); postos[posto_pessoal] = 0; //posto fica livre utentes[id_pessoal].saiu = 1; //sai do centro } } } } if(utentes[id_pessoal].posto_testagem == 0){ //Não está no ponto de testagem ------------------------- //verificar se já esperou o tempo nas configurações if(tempo_no_centro >= config.TEMPO_ATENDIMENTO){ //verificar se o posto está cheio, se nao estiver entra com o semaforo sem_wait(&fila_prio); //=================================================================================== int x; for(x = 0; x < config.NUMERO_POSTOS_TESTAGEM; x++){ if(postos[x] == 0){ postos[x] = 1; posto_pessoal = x; utentes[id_pessoal].posto_testagem = 1; printf("Utente %d entrou no posto de testagem %d \n",id_pessoal,x); numUtentesFilaPriori--; break; } } sem_post(&fila_prio); //=================================================================================== } } } else{ //Não tem prioridade if(utentes[id_pessoal].posto_testagem == 2){ //Se essa pessoa já teve no posto de testagem printf("Utente %d já teve no posto de testagem e vai para o isolamento \n",id_pessoal); if(utentes[id_pessoal].sala_isolamento == 1){ //Se está no isolamento if(utentes[id_pessoal].internamento == 1){ //Se está no internamento } else{ //Se está não está no internamento } } else{ //Não está no isolamento } } if(utentes[id_pessoal].posto_testagem == 1){ //Está no ponto de testagem ------------------------------ printf("Utente %d está no ponto de testagem \n",id_pessoal); //verificar teste do utilizador if(utentes[id_pessoal].tipo_teste == 0){ //utente faz teste convencional if(tempo_no_posto_de_testagem < config.TEMPO_TESTE_CONVENCIONAL){ //espera para fazer o teste convencional pthread_mutex_lock(&mutex_utente); tempo_no_posto_de_testagem++; pthread_mutex_unlock(&mutex_utente); } else{ printf("O utente %d recebeu o resultado do teste convecional \n",id_pessoal); int random_covid; random_covid = random_num(0,100); //probabilidade de ter covid positivo if(random_covid <= config.PROB_UTENTE_TER_COVID){ utentes[id_pessoal].covid= 1; printf("O utente %d tem covid positivo \n \n",id_pessoal); } else{ printf("O utente %d nao tem covid \n", id_pessoal); postos[posto_pessoal] = 0; //posto fica livre utentes[id_pessoal].saiu = 1; //sai do centro } } } else{ //utente faz teste_rápido if(tempo_no_posto_de_testagem < config.TEMPO_TESTE_RAPIDO){ //espera para fazer o teste rápido pthread_mutex_lock(&mutex_utente); tempo_no_posto_de_testagem++; pthread_mutex_unlock(&mutex_utente); } else{ printf("O utente %d recebeu o resultado do teste rápido \n",id_pessoal); int random_covid; random_covid = random_num(0,100); //probabilidade de ter covid positivo if(random_covid <= config.PROB_UTENTE_TER_COVID){ utentes[id_pessoal].covid= 1; printf("O utente %d tem covid positivo \n \n",id_pessoal); } else{ printf("O utente %d nao tem covid \n", id_pessoal); postos[posto_pessoal] = 0; //posto fica livre utentes[id_pessoal].saiu = 1; //sai do centro } } } } if(utentes[id_pessoal].posto_testagem == 0){ //Não está no ponto de testagem ------------------------- //verificar se já esperou o tempo nas configurações if(tempo_no_centro >= config.TEMPO_ATENDIMENTO){ //verificar se o posto está cheio, se nao estiver entra com o semaforo sem_wait(&fila_normal); //=================================================================================== int x; for(x = 0; x < config.NUMERO_POSTOS_TESTAGEM; x++){ if(postos[x] == 0){ postos[x] = 1; posto_pessoal = x; utentes[id_pessoal].posto_testagem = 1; printf("Utente %d entrou no posto de testagem %d \n",id_pessoal,x); numUtentesFilaNormal--; break; } } sem_post(&fila_normal); //=================================================================================== } } } } else{ printf("Utente %d saiu. \n",id_pessoal); pthread_cancel(pthread_self()); } } } void criasocket(){ int socket_desc , client_sock , c , read_size; struct sockaddr_in server , client; char client_message[2000]; //Criar socket socket_desc = socket(AF_INET , SOCK_STREAM , 0); if (socket_desc == -1) { printf("Não foi possivel criar o socket"); } puts("Socket criado"); //Preparar sockaddr_in na estrutura server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons( 8888 ); //Bind if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0) { perror("Bind falhou"); return 1; } puts("Bind completo \n"); //Listen listen(socket_desc , 3); //Aceitar conexões puts("Esperando conexões..."); c = sizeof(struct sockaddr_in); client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c); if (client_sock < 0) { perror("Falha ao aceitar"); return 1; } puts("Conexão aceite"); //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX //Receber mensagem do cliente while( (read_size = recv(client_sock , client_message , 2000 , 0)) > 0 ) { int opcao = atoi(client_message); if(opcao == 1 && iniciado == 1){ opcao = 2; sprintf(client_message, "%d", opcao); //int para str } if(opcao == 1 && iniciado == 0){ iniciado = 1; } switch(opcao){ case 1 : { //Iniciar simulação //Enviar o evento da abertura do centro write(client_sock , client_message , strlen(client_message)+1); break; } case 2: { //Continuar a simulacao int numero_random = random_num(1,1); int i = 0; for (i = 0; i < numero_random; i++){ pthread_t thread; pthread_create(&thread, NULL, &gerar_utentes, NULL); } //Função para gerar aleatoriamente um ou mais utentes com threads write(client_sock , client_message , strlen(client_message)+1); imprime_utentes(); tempo_universal++; break; } case 3: { //Pausar a simulacao break; } case 5: { printf("Terminando com o codigo: %d \n",opcao); exit(0); break; } } //----------------Comunicação------------------- //Tempo ++ } if(read_size == 0) { puts("Cliente desconectou"); fflush(stdout); } else if(read_size == -1) { perror("recv falhou"); } return 0; } int main(int argc, char **argv) { //LOAD CONFIGURAÇÃO int *conf = load_conf_simulador(argv[1]); config.TEMPO_MEDIO_CHEGADA_UTENTES = conf[0]; config.NUMERO_POSTOS_TESTAGEM = conf[1]; config.NUMERO_CENTROS_TESTAGEM = conf[2]; config.NUMERO_MAX_TESTES_PESSOA = conf[3]; config.MAX_PESSOAS_FILA = conf[4]; config.MAX_PESSOS_FILA_PRIORITARIA = conf[5]; config.PROB_UTENTE_TER_COVID = conf[6]; config.PROB_UTENTE_SER_PRIO = conf[7]; config.ATUALIZACAO_RESULTADO = conf[8]; config.NUMERO_MAX_DOENTES_INTERNAMENTO = conf[9]; config.NUMERO_MAX_ISOLAMENTO = conf[10]; config.TEMPO_ATENDIMENTO = conf[11]; config.TEMPO_ISOLAMENTO = conf[12]; config.TEMPO_TESTE_RAPIDO = conf[13]; config.TEMPO_TESTE_CONVENCIONAL = conf[14]; printf ("Load das configurações:\n"); int loop; for (loop = 0; loop < NUMBER_OF_CONFIGS; loop++){ printf("%d ", conf[loop]); } printf ("\n"); printf("Load postos de testagem \n"); int x; for(x = 0; x < config.NUMERO_POSTOS_TESTAGEM; x++){ postos[x] = 0; printf("Posto %d criado com valor %d \n",x,postos[x]); } sem_init(&fila_normal,0,1); sem_init(&fila_prio,0,1); sem_init(&fila_isolamento_normal,0,1); sem_init(&fila_isolamento_prio,0,1); criasocket(); sem_destroy(&fila_normal); sem_destroy(&fila_prio); sem_destroy(&fila_isolamento_normal); sem_destroy(&fila_isolamento_prio); }
C
/* row wise gaus algorithm * pattern for practical course * ------------------------- * autor: Markus Brenk * date: 2002-09-25 * =================================================== */ //#define NGLS 32768 #define NGLS 32800 #define NUM_LOOPS 4 #include <stdio.h> #include <math.h> #include "timer.h" /* print a 3x3 matrix */ void print_matrix(char* name, double matrix[3][3]); /* print a 3d vector */ void print_vector(char* name, double vec[3]); /** * initialisation: generates the following LGS: * ( 3 1 1) (5) (1) * ( 1 4 1) * X = (6) => solution X = (1) * ( 1 1 5) (7) (1) */ void init(double a[3][3], double b[3], double x[3]); /** performs gauss elimination */ void gauss_elimination(double a[3][3], double b[3], double x[3]); struct SoA{ //SoA double x[NGLS]; double y[NGLS]; double z[NGLS]; }; int main() { // COMPILE WITH //icc -std=c99 -O3 -qopt-report=5 -qopt-report-phase=vec gauss.c timer.h timer.c -o gauss double a[NGLS][3][3]; double b[NGLS][3]; double x[NGLS][3], L[3][3], U[3][3]; double y[3]; struct SoA new_b; struct SoA new_x; int i, j,k; int n=3; double sum; time_marker_t time; for (i = 0; i < NGLS; i++) { init(a[i], b[i], x[i]); } for (i = 0; i < NGLS; i++) { new_b.x[i] = b[i][0]; new_b.y[i] = b[i][1]; new_b.z[i] = b[i][2]; new_x.x[i] = x[i][0]; new_x.y[i] = x[i][1]; new_x.z[i] = x[i][2]; } time = get_time(); int iteration; for (iteration = 0; iteration < NGLS; iteration++) { for (i = 0; i < n; i++) { for (j = i+1; j < n; j++) { a[iteration][i][j] = a[iteration][i][j] / a[iteration][i][i]; } if (i==0) new_b.x[iteration] = new_b.x[iteration] / a[iteration][i][i]; else if (i==1) new_b.y[iteration] = new_b.y[iteration] / a[iteration][i][i]; else new_b.z[iteration] = new_b.z[iteration] / a[iteration][i][i]; for (j = i+1; j < n; j++) { double factor = a[iteration][j][i]; for (k = i; k < n; k++) { a[iteration][j][k] = a[iteration][j][k] - a[iteration][i][k] * factor; } double subtraction; if (i==0) subtraction = factor*new_b.x[iteration]; else if (i==1) subtraction = factor*new_b.y[iteration]; else subtraction = factor*new_b.z[iteration]; if (j==0) new_b.x[iteration] = new_b.x[iteration] - subtraction; else if (j==1) new_b.y[iteration] = new_b.y[iteration] - subtraction; else new_b.z[iteration] = new_b.z[iteration] - subtraction; } } for (i = n-1; i >= 0; i--) { if (i==0) new_x.x[iteration] = new_b.x[iteration]; else if (i==1) new_x.y[iteration] = new_b.y[iteration]; else new_x.z[iteration] = new_b.z[iteration]; for(j = i+1; j < n; j++) { double value; if (j==0) value = a[iteration][i][j] * new_x.x[iteration]; else if (j==1) value = a[iteration][i][j] * new_x.y[iteration]; else value = a[iteration][i][j] * new_x.z[iteration]; if (i==0) new_x.x[iteration] = new_x.x[iteration] - value; else if (i==1) new_x.y[iteration] = new_x.y[iteration] - value; else new_x.z[iteration] = new_x.z[iteration] - value; } } } //printf("%f %f %f\n", new_x.x[10],new_x.y[10],new_x.z[10]); printf("Vectorized Gauss: Time elapsed. time: %f ticks: %f\n", get_ToD_diff_time(time), get_ticks_diff_time(time)); return(0); } void init(double a[3][3], double b[3], double x[3]) { int i,j; int n = 3; for (j=0;j<n;j++) { b[j]=(float)(2*n-2)+(float)(j+1); a[j][j]=(float)(n-1)+(float)(j+1); x[j]=0.; for (i=j+1;i<n;i++) { a[i][j]=1.; } for (i=0;i<j;i++) { a[i][j]=1.; } } } void gauss_elimination(double a[3][3], double b[3], double x[3]) { int n = 3; int i,j,k; //print_matrix("before",a); for (i = 0; i < n; i++) { for (j = i+1; j < n; j++) { a[i][j] = a[i][j] / a[i][i]; } b[i] = b[i] / a[i][i]; //print_matrix("first substituiton",a); for (j = i+1; j < n; j++) { double factor = a[j][i]; for (k = i; k < n; k++) { a[j][k] = a[j][k] - a[i][k] * factor; } b[j] = b[j] - factor * b[i]; } //print_matrix("after 1 cycle a",a); //print_vector("after 1 cycle b",b); } for (i = n-1; i >= 0; i--) { x[i] = b[i]; for(j = i+1; j < n; j++) { //printf("a,i,j: %f\n",a[i][j]); x[i] -= a[i][j] * x[j]; } } } void print_matrix(char* name, double matrix[3][3]) { int i, j; printf("Matrix %s: \n", name); for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { printf(" %f ", matrix[i][j]); } printf(" ;\n"); } } void print_vector(char* name, double vec[3]) { int i; printf("vector %s: \n", name); for (i=0;i<3;i++) { printf(" %f \n",vec[i]); } }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include "header.h" /* Esta función se encarga de seleccionar dónde y de qué forma se debe leer el archivo de entrada para la carga de memoria y delega dichas tareas a otras funciones. Recibe como argumentos un archivo_t que indica el formato de entrada, una cadena con el nombre del archivo y un puntero a la estructura del simpletron. Retorna por el nombre el estado de la función. */ status_t leer_archivo(char *nombre_archivo_entrada, const archivo_t tipo_archivo_entrada, palabras_s *palabra) { status_t status; switch (tipo_archivo_entrada) { /*Si se ingreso -if bin*/ case ARCHIVO_BIN: /*ENTRADA stdin*/ if (strcmp(nombre_archivo_entrada, STR_STDIN) == 0) { return ST_ERROR_I_BIN_IF_NO_VALIDO; } /*ENTRADA archivo*/ status = cargar_estructura_bin(palabra, nombre_archivo_entrada); break; /*Si se ingreso -if txt*/ case ARCHIVO_TXT: /*ENTRADA stdin*/ if (strcmp(nombre_archivo_entrada, STR_STDIN) == 0) { status = cargar_estructura_stdin(palabra); break; } else /*ENTRADA archivo*/ status = cargar_estructura_txt(&palabra, nombre_archivo_entrada); break; default: status = ST_ERROR_ARCHIVO_NO_ENCONTRADO; } return status; } /* Esta función carga la memoria del simpletron desde un archivo con formato de texto. La función recibe un puntero doble a estructura (simpletron) y una cadena con el nombre del archivo de entrada. Retorna por el nombre el estado de la función. */ status_t cargar_estructura_txt(palabras_s** palabra, char *nombre_archivo_entrada) { char * pch, *linea; FILE * archivo_entrada; int i = 0, j; /*Compruebo si el archivo existe*/ if ((archivo_entrada = fopen(nombre_archivo_entrada, "r")) == NULL) return ST_ERROR_ARCHIVO_NO_ENCONTRADO; linea = (char*) malloc(sizeof (char)*MAX_STR); if (linea == NULL) return ST_ERROR_MEM; if (((*palabra)->memoria = (int*) malloc(sizeof (int))) == NULL) return ST_ERROR_MEM; /*Obtengo una linea a la vez del archivo*/ while (!feof(archivo_entrada) && (i < (*palabra)->cantidad_memoria)) { if ((fgets(linea, MAX_STR, archivo_entrada)) != NULL) { /*Descarto los comentarios*/ pch = strtok(linea, INICIO_COMENTARIO); /*Guardo la palabra en la estructura*/ (*palabra)->memoria[i] = strtol(linea, &pch, 10); i += 1; /*Pido memoria para agregar luego una palabra mas*/ if (((*palabra)->memoria = (int*) realloc((*palabra)->memoria, sizeof (int)*(i + 1))) == NULL) return ST_ERROR_MEM; } } /*Cargo el resto de la memoria pedida con ceros*/ for (j = i; j < (*palabra)->cantidad_memoria; j++) { if (((*palabra)->memoria = (int*) realloc((*palabra)->memoria, sizeof (int)*(j + 1))) == NULL) return ST_ERROR_PTR_NULO; (*palabra)->memoria[j] = 0; } fclose(archivo_entrada); free(linea); return ST_OK; } /* Esta función carga la memoria del simpletron desde un archivo con formato binario. La función recibe un puntero a estructura (simpletron) y una cadena con el nombre del archivo de entrada. Retorna por el nombre el estado de la función. */ status_t cargar_estructura_bin(palabras_s* palabra, char* nombre_archivo_entrada) { /*El archivo esta compuesto por enteros*/ int i = 0, j; FILE * archivo_entrada_bin; /*Compruebo si dicho archivo binario pasado por la terminal existe*/ if ((archivo_entrada_bin = fopen(nombre_archivo_entrada, "rb")) == NULL) return ST_ERROR_ARCHIVO_NO_ENCONTRADO; if ((palabra->memoria = (int*) malloc(sizeof (int))) == NULL) return ST_ERROR_MEM; while (!feof(archivo_entrada_bin) && (i < palabra->cantidad_memoria)) { /*Pido memoria en el vector para guardar una palabra mas*/ if ((palabra->memoria = (int*) realloc(palabra->memoria, sizeof (int)*(i + 1))) == NULL) return ST_ERROR_MEM; /*Guardo la palabra leida en la estructura*/ if ((fread(&palabra->memoria[i], sizeof (int), 1, archivo_entrada_bin)) == 1) i++; } /*Cargo el resto de la memoria pedida con ceros*/ for (j = i; j < palabra->cantidad_memoria; j++) { if ((palabra->memoria = (int*) realloc(palabra->memoria, sizeof (int)*(j + 1))) == NULL) return ST_ERROR_PTR_NULO; palabra->memoria[j] = 0; } fclose(archivo_entrada_bin); return ST_OK; } /* Esta función carga la memoria del simpletron desde stdin con formato de texto. La función recibe un puntero a estructura (simpletron). Retorna por el nombre el estado de la función. */ status_t cargar_estructura_stdin(palabras_s *palabras) { char *palabra_ingresada, *pch; int i = 0, aux; if ((palabra_ingresada = (char*) malloc(sizeof (char)*MAX_STR)) == NULL) return ST_ERROR_MEM; if ((palabras->memoria = (int*) malloc(sizeof (int))) == NULL) return ST_ERROR_MEM; printf("%s\n",MSJ_BIENVENIDO_SIMPLETRON); printf("%02d ? ", i); fgets(palabra_ingresada, MAX_STR, stdin); while (i < palabras->cantidad_memoria) { if ((strcmp(palabra_ingresada, FINALIZAR_CARGA)) != 0) { /*Pido memoria para guardar una palabra*/ aux = strtol(palabra_ingresada, &pch, 10); /*Valido que contenga solamente un entero*/ if (strlen(pch) == 1) { palabras->memoria[i] = aux; i++; /*Pido memoria para guardar una palabra*/ if ((palabras->memoria = (int*) realloc(palabras->memoria, sizeof (int)*(i + 1))) == NULL) return ST_ERROR_MEM; } /*Si no fue entero, ingresa nuevamente*/ else { fprintf(stdout, "%s\n", MSJ_ERROR_INGRESO_PALABRA); } /*Pido al usario que ingrese otra palabra*/ printf("%02d ? ", i); fgets(palabra_ingresada, MAX_STR, stdin); } else break; } /*Relleno el resto del vector con ceros*/ for (; i < palabras->cantidad_memoria; i++) { if ((palabras->memoria = (int*) realloc(palabras->memoria, sizeof (int)*(i + 1))) == NULL) return ST_ERROR_MEM; palabras->memoria[i] = 0; } /*Se libera la memoria pedida para la variable auxiliar*/ free(palabra_ingresada); return ST_OK; }
C
/** * All functions you make for the assignment must be implemented in this file. * Do not submit your assignment with a main function in this file. * If you submit with a main function in this file, you will get a zero. */ #include "sfmm.h" #include <stdio.h> #include <stdlib.h> #include <string.h> /** * You should store the heads of your free lists in these variables. * Doing so will make it accessible via the extern statement in sfmm.h * which will allow you to pass the address to sf_snapshot in a different file. */ free_list seg_free_list[4] = { {NULL, LIST_1_MIN, LIST_1_MAX}, {NULL, LIST_2_MIN, LIST_2_MAX}, {NULL, LIST_3_MIN, LIST_3_MAX}, {NULL, LIST_4_MIN, LIST_4_MAX} }; int sf_errno = 0; int page_track = 0; // int space = 0; void ptr_check(void *); void *sf_malloc(size_t size) { int space = 0; if(size == 0 || size > 16384){ sf_errno = 22; /*ENOMEM = 12*/ return NULL; } sf_header *header1; void *pay_load; //FINDING THE BLOCK SIZE BY ADDING 8 BYTES FOR HEADER AND FOOTER int size_1 = (int)size + 8 + 8; int padding = 0; if(size_1 % 16 != 0){ size_1 = size_1 + (16 - size_1%16); padding = 1; } int flag = 0; sf_free_header *cursor1; //SEE IF ANY LIST HAS A BLOCK TO RETURN FROM THE REQUESTED SIZE here:; for(int i = 0; i < 4;i++){ cursor1 = seg_free_list[i].head; while(flag == 0 && cursor1 != NULL){ if(((cursor1->header).block_size) << 4 >= size_1){ seg_free_list[i].head = seg_free_list[i].head->next; pay_load = (char*)cursor1 + 8; flag = 1; break; }else{ cursor1 = seg_free_list[i].head->next; } } if(flag == 1){ space = (cursor1->header).block_size << 4; break; } } //IF THE REQUESTED BLOCK SIZE WAS NOT FOUND IN THE LISTS int remaining_block = 0; int enough = 0; void *page; int colBlock = 0;; sf_header *temp_header; while(enough == 0 && flag == 0){ page = sf_sbrk(); space += 4096; remaining_block = space - size_1; page_track++; if(page_track>4){ sf_errno = 12; return NULL; }else{ temp_header = page; //CHECK IF PREVIOUS SPACE BLOCK IS FREE sf_footer *temp_footer = (sf_footer*)((char*)page - 8); //PROBLEM HERE int allocated_check = temp_footer->allocated; //IF BLOCK PREVIOUS TO START OF PAGE IS FREE THAN ENTER if(allocated_check == 0){ temp_header = (sf_header*)((char*)page - (temp_footer->block_size << 4)); //START SEARCHING LISTS TO FIND THE PREVIOUS BLOCK for(int i = 0;i < 4;i++){ sf_free_header *cursor = seg_free_list[i].head; if(&(cursor->header) == temp_header){ //SIZE_1 HAD THE TOTAL SIZE NEEDED FOR THE BLOCK TO BE RETURNED //FOUND SOME SPACE IN PREVIOUS BLOCK SO REQUIRED SIZE FROM NEW BLOCK IS SIZE_1 - BLOCK SIZE remaining_block = remaining_block + (cursor->header.block_size << 4); seg_free_list[i].head = cursor->next; colBlock = (temp_header->block_size << 4); break; } } } sf_header *header3 = (sf_header*)((char*)temp_header); header3-> allocated = 0; header3-> padded = 0; header3-> two_zeroes = 0; header3-> block_size = (colBlock + 4096) >> 4; header3-> unused = 0; sf_footer *footer3 = (void*)((char*)header3 + ((header3->block_size) << 4) - 8); footer3-> allocated = 0; footer3-> padded = 0; footer3-> two_zeroes = 0; footer3-> block_size = (colBlock + 4096) >> 4; footer3-> requested_size = 0; for(int i = 0; i < 4;i++){ if(seg_free_list[i].min <= (header3->block_size << 4) && seg_free_list[i].max >= (header3->block_size <<4)){ ((sf_free_header*)header3)->next = seg_free_list[i].head; if(!(seg_free_list[i].head == NULL)){ seg_free_list[i].head->prev = (sf_free_header*)header3; } seg_free_list[i].head = (sf_free_header*)header3; } } goto here; // if(space >=size_1){ // enough = 1; // } } } if(flag == 1){ temp_header = &cursor1->header; remaining_block = (cursor1->header.block_size << 4) - size_1; } header1 = temp_header; header1->allocated = 1; header1-> padded = padding; header1->two_zeroes = 0; if(remaining_block <= 16){ header1->block_size = space >> 4; padding = 1; header1-> padded = padding; }else{ header1->block_size = size_1 >> 4; } pay_load = (char*)header1 + 8; sf_footer *footer; if(remaining_block <=16){ footer = (sf_footer*)((char*)header1 + space - 8); padding = 1; }else{ footer = (sf_footer*)((char*)header1 + size_1 - 8); } footer->allocated = 1; footer-> padded = padding; footer->two_zeroes = 0; if(remaining_block <= 16){ footer->block_size = space >> 4; }else{ footer->block_size = size_1 >> 4; } pay_load = (char*)header1 + 8; footer->requested_size = size; int i = 0; for(i = 0; i < 4;i++){ if(seg_free_list[i].min <= remaining_block && seg_free_list[i].max >= remaining_block){ break; } } if(!(remaining_block <= 16)){ sf_header *header2 = (sf_header*)((char*)footer + 8); header2->allocated = 0; header2-> padded = 0; header2->two_zeroes = 0; header2->block_size = remaining_block >> 4; header2->unused = 0; sf_footer *footer2 = (void*)((char*)header2 + ((header2->block_size) << 4) - 8); footer2->allocated = 0; footer2-> padded = 0; footer2->two_zeroes = 0; footer2->block_size = remaining_block >> 4; footer2->requested_size = 0; ((sf_free_header*)header2)->next = NULL; ((sf_free_header*)header2)->prev = NULL; if(seg_free_list[i].head == NULL){ seg_free_list[i].head = (sf_free_header*)header2; }else{ ((sf_free_header*)header2)->next = seg_free_list[i].head; seg_free_list[i].head->prev = (sf_free_header*)header2; seg_free_list[i].head = (sf_free_header*)header2; } } sf_blockprint(header1); sf_snapshot(); return pay_load; } void *sf_realloc(void *ptr, size_t size) { //BLOCK IS ALREADY FREE ptr_check(ptr); sf_header *header = (sf_header*)((char*)ptr - 8); sf_footer *footer = (sf_footer*)((char*)header + (header->block_size << 4) - 8); void *ret; int padding = 0; if(size == 0){ sf_free(ptr); return NULL; } int size_1 = (int)size + 8 + 8; if(size_1 % 16 != 0){ size_1 = size_1 + (16 - size_1%16); padding = 1; } if(size_1 > (header->block_size <<4)){ ret = sf_malloc(size); if(ret != NULL){ memcpy(ret, ptr, header->block_size << 4); sf_free(ptr); } }else{ //SPLINTER CREATED SO DONT SPLIT if((header->block_size << 4) - size_1 < 32){ return ptr; } //REMAINING BLOCK IS BIGGER AND SMALLER NEED TO BE ADDED TO LIST else{ int remaining_block =(header->block_size << 4) - size_1; header->allocated = 1; header->padded = padding; header->two_zeroes = 0; header->block_size = size_1 >> 4; header->unused = 0; footer = (sf_footer*)((char*)header + (header->block_size << 4) - 8); footer->allocated = 1; footer-> padded = padding; footer->two_zeroes = 0; footer->block_size = size_1 >> 4; footer->requested_size = size; sf_header *header2 = (sf_header*)((char*)footer + 8); header2->allocated = 1; header2-> padded = 1; header2->two_zeroes = 0; header2->block_size = remaining_block >> 4; header2->unused = 0; sf_footer *footer2 = (void*)((char*)header2 + ((header2->block_size) << 4) - 8); footer2->allocated = 1; footer2-> padded = 1; footer2->two_zeroes = 0; footer2->block_size = remaining_block >> 4; footer2->requested_size = 0; sf_free((char*)header2 + 8); ret = (char*)header + 8; } } return ret; } void sf_free(void *ptr) { sf_header *header = (sf_header*)((char*)ptr - 8); sf_footer *footer = (sf_footer*)((char*)header + (header->block_size << 4) - 8); int block_size1 = 0; //BLOCK IS ALREADY FREE ptr_check(ptr); header->allocated = 0; header-> padded = 0; header->two_zeroes = 0; ((sf_free_header*)header)->next = NULL; ((sf_free_header*)header)->prev = NULL; header->unused = 0; footer->allocated = 0; footer-> padded = 0; footer->two_zeroes = 0; footer->requested_size = 0; block_size1 = header->block_size << 4; sf_header *header2 = (sf_header*)((char*)footer + 8); if(header2->allocated == 0){ block_size1 = (header->block_size << 4) + (header2->block_size << 4); footer = (sf_footer*)((char*)header2 + (header2->block_size << 4) - 8); header->block_size = block_size1 >> 4; footer->block_size = block_size1 >> 4; } for(int i = 0;i < 4;i++){ sf_free_header *cursor = seg_free_list[i].head; while(cursor != NULL){ if(&(cursor->header) == header2){ if(cursor->prev!=NULL){ (cursor->prev)->next = cursor->next; (cursor->next)->prev = cursor->prev; }else{ seg_free_list[i].head = seg_free_list[i].head->next; } } cursor = cursor->next; } } int i = 0; for(i = 0; i < 4;i++){ if(seg_free_list[i].min <= block_size1 && seg_free_list[i].max >= block_size1){ ((sf_free_header*)header)->next = seg_free_list[i].head; seg_free_list[i].head = (sf_free_header*)header; } } sf_snapshot(); return; } void ptr_check(void *ptr){ if(ptr == NULL){ abort(); } sf_header *header = (sf_header*)((char*)ptr - 8); if(header->allocated == 0){ abort(); } sf_footer *footer = (sf_footer*)((char*)header + (header->block_size << 4) - 8); if(footer->allocated == 0){ abort(); } else if(footer->requested_size + 16 != footer->block_size << 4){ if(!(footer->padded == 1)){ abort(); } } else if(header->allocated != footer->allocated && header->padded != footer->padded){ abort(); } }
C
#include<stdio.h> main(){ int n,i,count=0,k; printf("Enter the number"); scanf("%d",&n); for(i=0;i<32;i++){ k=((n>>i)&1); if(k==1){ break; } if(k==0){ count++; } } printf("The trailing zero are %d",count); }
C
#include "../incs/philo.h" static int init_semaphores_for_philos(t_info *info) { int idx; char sem_name[255]; idx = -1; while (++idx < info->num_of_philos) { memset(sem_name, 0, 255); gen_name_tag(sem_name, SEM_PHILO_EAT, idx); info->philos[idx].eat_mutex = ft_sem_open(sem_name, 1); sem_unlink(sem_name); if ((info->philos[idx].eat_mutex) < 0) return (ERR_SEM_OPEN); if (sem_wait(info->philos[idx].eat_mutex)) return (ERR_SEM_DO); } return (0); } static int init_semaphores(t_info *info) { sem_unlink(SEM_FORK); sem_unlink(SEM_MSG); sem_unlink(SEM_SOMEONE_DEAD); if ((info->fork_mutexes = ft_sem_open(SEM_FORK, info->num_of_philos)) < 0 || (info->msg_mutex = ft_sem_open(SEM_MSG, 1)) < 0 || (info->someone_dead_mutex = ft_sem_open(SEM_SOMEONE_DEAD, 1)) < 0 || init_semaphores_for_philos(info)) return (ERR_SEM_OPEN); if (sem_wait(info->someone_dead_mutex)) return (ERR_SEM_DO); return (0); } static int init_philos(t_info *info) { int idx; info->philos = (t_philo *)malloc(sizeof(t_philo) * info->num_of_philos); if (!info->philos) return (ERR_INIT_INFO); idx = -1; while (++idx < info->num_of_philos) { info->philos[idx].status = STATUS_THINK; info->philos[idx].pos = idx + 1; info->philos[idx].beg_eat_time = get_cur_time(); info->philos[idx].eat_cnt = 0; info->philos[idx].info = info; info->philos[idx].eat_finished = 0; } return (0); } int init_info( t_info *info, int argc, char *argv[]) { (void)argc; info->num_of_philos = ft_atoi(argv[1]); info->time_to_die = ft_atoi(argv[2]); info->time_to_eat = ft_atoi(argv[3]); info->time_to_sleep = ft_atoi(argv[4]); info->time_to_sleep = ft_atoi(argv[4]); info->num_of_must_eat = ft_atoi(argv[5]); if (init_philos(info)) return (ERR_INIT_INFO); return (init_semaphores(info)); }
C
#include "scop.h" static int load_tga_image( t_tga *tga, FILE *stream) { size_t size; size_t size_read; tga->buffer = NULL; size = tga->width * tga->height * 4; if (!(tga->buffer = (uint8_t*)malloc(sizeof(uint8_t) * size + 1))) return (-1); if ((size_read = fread(tga->buffer, 1, size, stream)) != size) { fprintf(stderr, "%ld has been read\n", size_read); return (-1); } return (0); } static void fill_tga_image(t_tga *tga) { size_t x; size_t y; size_t i; size_t z; x = 0; y = 0; z = (tga->height - 1) * tga->width * 4; i = 0; while (i < tga->width * tga->height) { if (x > tga->width - 1) { x = 0; z = (tga->height - (++y + 1)) * tga->width * 4; } tga->image[x + (y * tga->width)] = uint32_color( tga->buffer[z + (x * 4)], tga->buffer[z + (x * 4) + 3], tga->buffer[z + (x * 4) + 2], tga->buffer[z + (x * 4) + 1]); x++; i++; } } int load_tga_file_error( const char *pathname, FILE *stream) { fprintf(stderr, "Unable to load file %s\n", pathname); if (stream) fclose(stream); return (-1); } /* ** Load TGA file */ int load_tga_file( t_tga *tga, const char *pathname) { FILE *stream; printf("Start loading tga file %s\n", pathname); memset(tga, 0, sizeof(t_tga)); if ((stream = fopen(pathname, "rb")) == NULL) return (load_tga_file_error(pathname, stream)); if (fill_tga_header(tga, &tga->header, stream)) return (load_tga_file_error(pathname, stream)); if (tga->header.id_length != 0 && tga->header.color_map_type != 0 && tga->header.image_type != NON_COMPRESSED_TGA) return (load_tga_file_error(pathname, stream)); if (!(tga->image = (uint32_t*)malloc(sizeof(uint32_t) * tga->width * tga->height))) return (load_tga_file_error(pathname, stream)); load_tga_image(tga, stream); tga->buffer = decode_tga(tga); fill_tga_image(tga); free(tga->buffer); fclose(stream); return (0); }
C
#include "stdio.h" #include "stdlib.h" #include "locale.h" #include "conio.h" int main() { int N, M, N1, M1, i, j, k; setlocale(0, "RUS"); N = 10; int **A = (int**)malloc(N * sizeof(int*)); int **B = (int**)malloc(N * sizeof(int*)); int **C = (int**)malloc(N * sizeof(int*)); for (i = 0; i < N; i++) { A[i] = (int*)malloc(N * sizeof(int)); B[i] = (int*)malloc(N * sizeof(int)); C[i] = (int*)malloc(N * sizeof(int)); } printf(" : "); scanf("%d", &N); printf(" : "); scanf("%d", &M); printf(" A:\n"); for (i = 0; i < N; i++) for (j = 0; j < M; j++) { scanf("%d", &A[i][j]); } printf(" : "); scanf("%d", &N1); printf(" : "); scanf("%d", &M1); if (M != N1) printf(" "); else { printf(" B:\n"); for (i = 0; i < N1; i++) for (j = 0; j < M1; j++) { scanf("%d", &B[i][j]); } for (i = 0; i < N; i++) for (j = 0; j < M; j++) { C[i][j] = 0; for (k = 0; k < M1; k++) C[i][j] += A[i][k] * B[k][j]; } printf("\n \n"); for (i = 0; i < N; i++) { for (j = 0; j < M; j++) printf("%d ", A[i][j]); printf("\n"); } printf("\n B\n"); for (i = 0; i < N1; i++) { for (j = 0; j < M1; j++) printf("%d ", B[i][j]); printf("\n"); } printf("\n %dx%d\n", N, M1); for (i = 0; i < N; i++) { for (j = 0; j < M1; j++) printf("%d ", C[i][j]); printf("\n"); } _getch(); return 0; } }
C
#include "sailr.h" #include <CUnit/CUnit.h> #include <CUnit/Basic.h> void test_func_test1( void ); void test_func_add_tests(CU_pSuite testSuite) { CU_add_test(testSuite, "test funcs ", test_func_test1 ); } void test_func_test1( void ) { // Code const char* code = " " "space_pi = ' ' + str_subset(num_to_str(3.14),1,4) + num_to_str(1592) + num_to_str(6535) ;" "pi_str = 'PI is' + space_pi ;" "pi_num = str_to_num( str_strip(space_pi)) ;" "three_str = str_subset( num_to_str(10/3) , 1 , 4);" "seven_str = str_repeat( num_to_str(7), 7);" "ten_str = num_to_str( 2.5 * 4 ) \n" "\n" "spaced_str = ' hello world ';" "stripped_str = str_strip(spaced_str);" "jpn_hello = 'こんにちは';" "new_str = str_concat( jpn_hello, ' ' , stripped_str );" "new_str2 = str_concat( new_str, ', PI = ', pi_num);" ; // Parser Initialization ptr_table_object* table = sailr_ptr_table_init() ; parser_state_object* ps = sailr_new_parser_state ("souce from string literal", table); sailr_run_parser( code, ps ); // Add variables sailr_ptr_table_create_null(&table, "space_pi" ); sailr_ptr_table_create_null(&table, "pi_str" ); sailr_ptr_table_create_null(&table, "pi_num" ); sailr_ptr_table_create_null(&table, "three_str" ); sailr_ptr_table_create_null(&table, "seven_str" ); sailr_ptr_table_create_null(&table, "ten_str" ); sailr_ptr_table_create_null(&table, "spaced_str"); sailr_ptr_table_create_null(&table, "stripped_str"); sailr_ptr_table_create_null(&table, "jpn_hello"); sailr_ptr_table_create_null(&table, "new_str"); sailr_ptr_table_create_null(&table, "new_str2"); // Creating virtual machine codes vm_inst_object* inst_list = sailr_gen_code( ps, table); // VM Code is generated. vm_inst_object* vmcode = sailr_vm_inst_list_to_code(inst_list); int vmcode_size = sailr_vm_inst_list_size( inst_list); vm_stack_object* vmstack = sailr_vm_stack_init(); // Run sailr_vm_exec_code(vmcode, vmcode_size , table , vmstack, NULL); // Assert // sailr_ptr_table_show_all(&table); char st_space_pi = sailr_ptr_table_get_type(&table, "space_pi"); char st_pi_str = sailr_ptr_table_get_type(&table, "pi_str"); char st_pi_num = sailr_ptr_table_get_type(&table, "pi_num"); char st_three_str = sailr_ptr_table_get_type(&table, "three_str"); char st_seven_str = sailr_ptr_table_get_type(&table, "seven_str"); char st_ten_str = sailr_ptr_table_get_type(&table, "ten_str"); char st_spaced_str = sailr_ptr_table_get_type(&table, "spaced_str"); char st_stripped_str = sailr_ptr_table_get_type(&table, "stripped_str"); char st_new_str = sailr_ptr_table_get_type(&table, "new_str"); char st_new_str2 = sailr_ptr_table_get_type(&table, "new_str2"); CU_ASSERT_EQUAL( st_space_pi , 's'); CU_ASSERT_EQUAL( st_pi_str , 's'); CU_ASSERT_EQUAL( st_pi_num , 'd'); CU_ASSERT_EQUAL( st_three_str , 's'); CU_ASSERT_EQUAL( st_seven_str , 's'); CU_ASSERT_EQUAL( st_ten_str , 's'); CU_ASSERT_EQUAL( st_spaced_str , 's'); CU_ASSERT_EQUAL( st_stripped_str , 's'); CU_ASSERT_EQUAL( st_new_str , 's'); CU_ASSERT_EQUAL( st_new_str2 , 's'); const char* s_space_pi = sailr_ptr_table_read_string(&table, "space_pi"); const char* s_pi_str = sailr_ptr_table_read_string(&table, "pi_str"); double s_pi_num = *((double*) *sailr_ptr_table_get_pptr(&table, "pi_num")); const char* s_three_str = sailr_ptr_table_read_string(&table, "three_str"); const char* s_seven_str = sailr_ptr_table_read_string(&table, "seven_str"); const char* s_ten_str = sailr_ptr_table_read_string(&table, "ten_str"); const char* s_spaced_str = sailr_ptr_table_read_string(&table, "spaced_str"); const char* s_stripped_str = sailr_ptr_table_read_string(&table, "stripped_str"); const char* s_new_str = sailr_ptr_table_read_string(&table, "new_str"); const char* s_new_str2 = sailr_ptr_table_read_string(&table, "new_str2"); CU_ASSERT_STRING_EQUAL( s_space_pi , " 3.1415926535"); CU_ASSERT_STRING_EQUAL( s_pi_str , "PI is 3.1415926535"); CU_ASSERT_DOUBLE_EQUAL( s_pi_num , 3.1415926535, 0.00001 ); CU_ASSERT_STRING_EQUAL( s_three_str , "3.33"); CU_ASSERT_STRING_EQUAL( s_seven_str , "7777777"); CU_ASSERT_STRING_EQUAL( s_ten_str , "10.000000"); CU_ASSERT_STRING_EQUAL( s_spaced_str , " hello world "); CU_ASSERT_STRING_EQUAL( s_stripped_str , "hello world"); CU_ASSERT_STRING_EQUAL( s_new_str , "こんにちは hello world"); CU_ASSERT_STRING_EQUAL( s_new_str2 , "こんにちは hello world, PI = 3.141593" ); // Clean up sailr_tree_free(ps); sailr_ptr_table_del_all(&table); sailr_parser_state_free(ps); }
C
/* Recursive function for printing numbers in decreasing order*/ #include<stdio.h> int main() { int x; printf("Enter the number "); scanf("%d",&x); func(x); return 0; } void func(int n) { if(n > 0) { printf("%d \n",n); func(n-1); } }
C
#include "../../pagai_assert.h" int unknown1(); int unknown2(); int unknown3(); int unknown4(); /* * From CAV'12 by Sharma et al. */ void main() { int x=0; int y=0; int n = 0; while(unknown1()) { x++; y++; } while(x <= n - 1 || x >= n + 1) { x--; y--; } if(x != n) return; assert(y == n); }
C
#include<stdio.h> int main() { int a[100][100],i,j,r,c,count1=0,count2=0,f=0,k,rfi=0; int sparse1[100][3],sparse2[100][3],final[100][3],m=1,n=1; printf("Enter the number of rows : "); scanf("%d",&r); printf("\nEnter the number of columns : "); scanf("%d",&c); for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("\nEnter the element a[%d][%d] for Array 1 : ",i,j); scanf("%d",&a[i][j]); if(a[i][j]!=0) { count1++; } } printf("\n"); } sparse1[0][0]=r; sparse1[0][1]=c; sparse1[0][2]=count1; for(i=0;i<r;i++) { for(j=0;j<c;j++) { if(a[i][j]!=0) { sparse1[m][0]=i; sparse1[m][1]=j; sparse1[m][2]=a[i][j]; m++; } } } printf("\n\n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("\nEnter the element a[%d][%d] for Array 2 : ",i,j); scanf("%d",&a[i][j]); if(a[i][j]!=0) { count2++; } } printf("\n"); } sparse2[0][0]=r; sparse2[0][1]=c; sparse2[0][2]=count2; for(i=0;i<r;i++) { for(j=0;j<c;j++) { if(a[i][j]!=0) { sparse2[n][0]=i; sparse2[n][1]=j; sparse2[n][2]=a[i][j]; n++; } } } printf("\nMatrix 1: \n"); for(i=0;i<m;i++) { for(j=0;j<3;j++) { printf("%d ",sparse1[i][j]); } if(i==0) printf("\n-------"); printf("\n"); } printf("\nMatrix 2: \n"); for(i=0;i<n;i++) { for(j=0;j<3;j++) { printf("%d ",sparse2[i][j]); } if(i==0) printf("\n---------"); printf("\n"); } printf("\n\nAdded : - \n"); for(i=1;i<count1+1;i++) { f=0; for(k=1;k<count2+1;k++) { if((sparse1[i][0]==sparse2[k][0])&&(sparse1[i][1]==sparse2[k][1])) { f=1; break; } } final[i][0]=sparse1[i][0]; final[i][1]=sparse1[i][1]; if(f==0) { final[i][2]=sparse1[i][2]; } else { final[i][2]=sparse1[i][2]+sparse2[k][2]; } } for(i=1;i<count2+1;i++) { f=0; for(j=1;j<count1+1;j++) { if((sparse2[i][0]==final[j][0])&&(sparse2[i][1]==final[j][1])) { f=1; break; } } if(f==0) { final[count1+1][0]=sparse2[i][0]; final[count1+1][1]=sparse2[i][1]; final[count1+1][2]=sparse2[i][2]; count1++; } } final[0][0]=count1; final[0][1]=c; final[0][2]=count1; printf("%d ",final[0][0]); printf("%d ",final[0][1]); printf("%d ",final[0][2]); printf("\n---------\n"); for(i=1;i<count1+1;i++) { for(j=0;j<3;j++) { printf("%d ",final[i][j]); } printf("\n"); } return 0; }
C
#include<stdio.h> void tower(int, char, char, char); int c; int main() { system("clear"); int n; printf("\nLet:\nS be the starting Peg,on which n disks are placed initially."); printf("\nA be the Auxiliary Peg that will be utilized as intermediate peg."); printf("\nD be the Destination Peg on which n disks to be moved."); printf("\nEnter the number of disks in the peg S: "); scanf("%d", &n); tower(n, 'S', 'A', 'D'); printf("\nTotal no. of steps: %d\n",c); return(0); } void tower(int n,char c1, char c2, char c3) { if(n == 1) { printf("\nStep %d: %c->%c ",++c, c1, c3); return; } tower(n - 1, c1, c3, c2); printf("\nStep %d: %c->%c ",++c, c1, c3); tower(n - 1, c2 ,c1, c3); return; }
C
#include <stdio.h> int main(void) { //ȭ . // nCUTOFF ! const int nCUTOFF = 70; int nInput = 0; printf(" Էϼ. : "); scanf("%d", &nInput); //'70'̶ Ȯ , 'հ ' // ǹ̸ ο ڵ带 ۼ ִ. if (nInput >= nCUTOFF) printf("հԴϴ.\n"); else printf("հԴϴ.\n"); return 0; }
C
#include <stdio.h> int max(int, int); int main() { int a, b; scanf("%d%d", &a, &b); printf("%d\n", max(a, b)); return 0; } int max (int a, int b) { if (a > b) return a; return b; }
C
#include <stdio.h> #include <stdlib.h> int** AllocMat(int Ligne, int Colonne){ int ** M = calloc(Ligne, sizeof(int*)); for(int i =0; i<Ligne; i++){ M[i] = (int*) calloc(Colonne, sizeof(int)); } return M; } void RandMat(int **tab, int Ligne, int Colonne, int a, int b){ for(int i =0; i<Ligne; i++){ for(int j = 0; j<Colonne; j++){ tab[i][j] = (rand() % (b - a + 1)) + a; } } } int ** lireMatrice(FILE * fichier, int ligne, int colonne){ fscanf(fichier, "\n"); printf("ouverture de la matrice \n" ); int ** matrice = AllocMat(ligne, colonne); for(int i = 0; i<ligne; i++){ for(int j = 0; j<colonne; j++){ fscanf (fichier, "%d", &matrice[i][j]); } //fscanf(fichier, "\n"); } fclose(fichier); return matrice; } void affMat(int ** matrice, int ligne, int colonne){ for(int i = 0; i<ligne; i++){ for(int j = 0; j<colonne; j++){ if(matrice[i][j] != 0){ printf("1"); } else{ printf("."); } } printf("\n"); } printf("\n" ); } void affSol(int ** matrice, int ligne, int colonne){ int h = 0; for(int i = 0; i <3; i++){ for(int j = 0; j <3; j++){ if(matrice[h][colonne-1] != 0){ printf("1"); } else{ printf("."); } h++; } printf("\n"); } printf("\n" ); }
C
#include<stdio.h> #include<math.h> int main() { int num,rem,sum=0,temp; printf("Enter a number:"); scanf("%d",&num); temp=num; while(temp!=0) { rem=temp%10; temp/=10; sum+=(rem*rem*rem); } if(sum==num) printf("\n%d is armstrong number",num); else printf("\n%d is not an armstrong number",num); return 0; }