language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <windows.h> char path[] = "C:\\WINDOWS\\system32\\notepad.exe" ; int main() { PROCESS_INFORMATION pif; STARTUPINFO si; printf("Current Process ID = %d\n", GetCurrentProcessId()); ZeroMemory(&si,sizeof(si)); si.cb = sizeof(si); // creat a process to run notepad printf("Creat a process to run notepad\n"); CreateProcess( path, NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pif); printf("process notepad id: %d\n", GetProcessId(pif.hProcess)); printf("Press any key to terminate notepad ...\n"); getch(); TerminateProcess(pif.hProcess,0); CloseHandle(pif.hProcess); CloseHandle(pif.hThread); ZeroMemory(&si,sizeof(si)); si.cb = sizeof(si); printf("Creat a process to run notepad\n"); CreateProcess( path, NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pif); printf("Waiting for notepad terminated\n"); WaitForSingleObject(pif.hProcess, INFINITE); CloseHandle(pif.hProcess); CloseHandle(pif.hThread); return 0; }
C
#include "SList.h" // return 1 on success, 0 on fail SContactList* add_contact_sl(SContactList* head, Contact* new_contact, int isCircular) { SContactList* cursor = head; if (cursor == NULL) { cursor = malloc(sizeof(SContactList)); if (cursor == NULL) return NULL; cursor->data = create_contact(new_contact->name, new_contact->surname, new_contact->city, new_contact->homeNumber); //free_contact(new_contact); if (isCircular == 1) cursor->next = cursor; else cursor->next = NULL; return cursor; } SContactList* new_node = malloc(sizeof(SContactList)); if (new_node == NULL) return NULL; new_node->data = new_contact; if (isCircular == 0) { if (cursor->next == NULL) { cursor->next = new_node; } else { while (cursor->next != NULL) { if (strcmp(cursor->data->surname, new_contact->surname) <= 0) { new_node->next = cursor->next; cursor->next = new_node; return head; } cursor = cursor->next; } cursor->next = new_node; return head; } } else { if (head->next == head) { head->next = new_node; new_node->next = head; return head; } else { while (cursor->next != head) { if (strcmp(cursor->data->surname, new_contact->surname) <= 0) { new_node->next = cursor->next; cursor->next = new_node; return head; } cursor = cursor->next; } new_node->next = cursor->next; cursor->next = new_node; return head; } } } int add_city_sl(SCityList* head, City* new_city, int isCircular) { if (head == NULL) { head = malloc(sizeof(SCityList)); if (head == NULL) return 0; head->data = new_city; if (isCircular == 1) head->next = head; else head->next = NULL; return 1; } SCityList* cursor = head; SCityList* new_node = malloc(sizeof(SCityList)); if (new_node == NULL) return 0; new_node->data = new_city; if (isCircular == 0) { while (cursor != NULL && strcmp(new_node->data->city, cursor->data->city) >= 0) cursor = cursor->next; } else { while (cursor != head && strcmp(new_node->data->city, cursor->data->city) >= 0) cursor = cursor->next; } new_node->next = cursor->next; cursor->next = new_node; return 1; } // return 1 on success, 0 on fail int remove_contact_sl(SContactList* head, char* name, char* surname, int isCircular) { SContactList* cursor = head; SContactList* prev; if (cursor == NULL) return 0; while (strcmp(cursor->data->name, name) != 0 && strcmp(cursor->data->surname, surname) != 0) { if(cursor == NULL) return 0; prev = cursor; cursor = cursor->next; } prev->next = cursor->next; cursor->next = NULL; // Free all values, I guess? free(cursor->data->name); free(cursor->data->surname); free(cursor->data->city); free(cursor->data->homeNumber); free(cursor->data); free(cursor); return 1; } int remove_city_sl(SCityList* head, char* city_name, int isCircular) { SCityList* cursor = head; SCityList* prev; if (cursor == NULL) return 0; while (strcmp(cursor->data->city, city_name) != 0) { if(cursor == NULL) return 0; prev = cursor; cursor = cursor->next; } prev->next = cursor->next; cursor->next = NULL; // Free all values, I guess? free(cursor->data->city); free(cursor->data); free(cursor); return 1; } // return data on success, NULL if fail Contact* search_contact_sl(SContactList* head, char* name, char* surname, int isCircular) { SContactList* cursor = head; if (cursor == NULL) return NULL; while (strcmp(cursor->data->name, name) != 0 && strcmp(cursor->data->surname, surname) != 0) { if(cursor == NULL) return NULL; cursor = cursor->next; } return cursor->data; } City* search_city_sl(SCityList* head, char* city_name, int isCircular) { SCityList* cursor = head; if (cursor == NULL) return 0; while (strcmp(cursor->data->city, city_name) != 0) { if(cursor == NULL) return 0; cursor = cursor->next; } return cursor->data; } // prints whole list, stops when next == NULL or next == head (when circular) void print_contact_sl(SContactList* head, SCityList* location, int isCircular) { SContactList* cursor = head; if (cursor == NULL) return; City* current_city; if (isCircular == 0) { while (cursor != NULL) { printf("\n"); current_city = search_city_sl(location, cursor->data->city, isCircular); print_contact(cursor->data, current_city); cursor = cursor->next; } } else { do { printf("\n"); current_city = search_city_sl(location, cursor->data->city, isCircular); print_contact(cursor->data, current_city); cursor = cursor->next; } while (cursor != head); } } void print_city_sl(SCityList* head, int isCircular) { SCityList* cursor = head; if (cursor == NULL) return; if (isCircular == 0) { while (cursor != NULL) { printf("\n"); print_city(cursor->data); cursor = cursor->next; } } else { do { printf("\n"); print_city(cursor->data); cursor = cursor->next; } while (cursor != head); } }
C
// // ex05.c // // Copyright (c) 2016 Insightbook. All rights reserved. // #include <stdio.h> #include <string.h> #include <stdlib.h> int main(int argc, const char * argv[]) { // Exercise 05 char num1[16], num2[16]; int number1, number2; int len; printf("What is the first number? "); fgets(num1, 16, stdin); len = strlen(num1); if (num1[len-1] == '\n') num1[len-1] = '\0'; printf("What is the second number? "); fgets(num2, 16, stdin); len = strlen(num2); if (num2[len-1] == '\n') num2[len-1] = '\0'; number1 = atoi(num1); number2 = atoi(num2); printf("%d + %d = %d\n%d - %d = %d\n%d * %d = %d\n%d / %d = %d\n", number1, number2, number1+number2, number1, number2, number1-number2, number1, number2, number1*number2, number1, number2, number1/number2); return 0; }
C
#include <string.h> extern char *getenv(const char *name); extern int foo(); extern int bar(); int main() { char *tainted = getenv("hi"); char *not_tainted1 = "hi"; memcpy(tainted, not_tainted1, 3); char *not_tainted2 = tainted; return 0; }
C
/* graph is an important data structure. We can judge the connection between 2 point; We can calculate minimum distance between 2 point; We can find different route based on different requirement. Sometimes We have to distract minimum tree from graph, then We don't need to judge if we meet loop node constantly. */ /* 1. graph based on matrix matrix is the simplest express method. If there are 5 point in a graph, we can build a 5x5 matrix. If there is connecion between points, then fill with 1; If there is no connection, we can use 0. Of course, the diagonal connecntion has no significant. */ static int graph[5][5] = { {0, 1, 0, 1, 1}, {1, 0, 1, 0, 1}, {0, 1, 0, 1, 0}, {1, 0, 1, 0, 1}, {1, 1, 0, 1, 0} }; /* If the connections between points have direction, then they are not symmetrical. */ static int graph[5][5] = { {0, 0, 0, 0, 0}, {1, 0, 0, 0, 0}, {0, 1, 0, 0, 0}, {1, 0, 1, 0, 0}, {1, 1, 0, 1, 0} }; /* If the connection between points has some kinds of relationship, such as distance, we can use it to replace 1. */ static int graph[5][5] = { {0, 0, 0, 0, 0}, {3, 0, 0, 0, 0}, {0, 6, 0, 0, 0}, {8, 0, 4, 0, 0}, {9, 2, 0, 7, 0} }; /* Matrix struct is visual, but it waste space. If there are 10000 node in a graph, we need 10000X10000 space, so it sacrifice space very much. */ /* 2. graph based on array. To avoid wasting space, we can build a data space only with lines. Such as: */ typedef struct _LINE { int start; int end; int weight; int isDirection; }LINE; /* start: is the start point end : is the end point weight: is the relationship. isDirection: used to judge if the edge has direction. How much lines in a graph, we need to define how much this data struct. If we put all the lines in a array, then we can use this array to express a whole graph. But this data structure pay more attention on line, and ignored start point. because the line information has no significant without start point. */ /* 3. graph based on list */ typedef struct _LINE { int end; int weight; struct _LINE* next; }LINE; typedef struct _VECTEX { int start; int number; LINE* neighbor; }VECTEX; /* VECTEX means a start point information. LINE means node information. If LINE is a variable in VECTEX, then neighbor means all the start point of the nodes is (int start). */ /* If the line is a viriable in PATH, then the start point of next, is the node before current line. */ typedef struct _PATH { int start; int end; int lenth; LINE* next; }PATH; /* notes: 1. array and list is the base of graph. 2. every data structure has it's own feature, the key is to understand the ideology and methods. 3. the expression of graph is the basic of graph computation. */
C
#include<stdio.h> int main() { //code int t; scanf("%d",&t); while(t>0){ long long int i,j,o=0,tw=0,z=0,n; scanf("%lld",&n); for(i=0;i<n;i++){ scanf("%lld",&j); if(j==0){ z++; } else if(j==1){ o++; } else{ tw++; } } //Jus count no of zero,one and two and print thm while(z>0||tw>0||o>0){ if(z>0){ printf("0 "); z--; } else if(o>0){ printf("1 "); o--; } else{ printf("2 "); tw--; } } printf("\n"); t--; } return 0; }
C
/********************************************************************************* * * Binary_Search.c * Author: Ahmed Nofal, Avelabs Embedded software R&D crew * ********************************************************************************/ /****************************[Problem Description]********************************* * * Binary search is one of the best searching algorithms. Binary search algorithm * works as follows: * Assume having a sorted array arr = [1, 2, 3, 4, 5, 6, 7] and you want to search * for the number "2" the algorithm starts by comparing your target number "2" to * the middle number in the array which is "4" if this is the desired number then * return the index of it, if not, is 2 greater than 4 ? no then is it less than 4? * Yes, then start looking in the sub array starting from the first element in the * array to the elment right before the middle element "4", i.e (1..arr[mid-1]). * Get the middle element in this sub-array and compare it to 2, is 2 equal to 2? * Yes then return the index of it. * As we can see Binary search found this number in 2 iterations only. * *Notice:: if you try searching for the element "6" you will reach it in only two * iterations ********************************************************************************/ #include <stdio.h> #include "Binary_Search.h" #include "Bubble_Sort.h" #define ARR_SIZE 12 int Linear_search_algo(int arr[], int arr_size, int target){ unsigned short i=0U; for(i=0U;i<arr_size;i++){ if(arr[i]==target){ return i; } } return -1; } int Binary_search_algo(int arr[], int arr_size, int target){ unsigned short i = 0; unsigned short first = 0; unsigned short last = arr_size-1U; unsigned short med = ((last-first)+!((last-first)%2))/2U; while((first <= last)){ if(arr[med] == target){ return med; } else if(target > arr[med]){ first=med+1; med = (((last-first)+!((last-first)%2))/2U)+first; } else{ last=med-1; med = (((last-first)+!((last-first)%2))/2U)+first; } } return -1; }
C
#include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <limits.h> #include <stdbool.h> typedef struct Node { int data; struct Node* next; }Node; Node* removeDuplicates(Node *head){ //Write your code here if (!head) return head; Node *tmp = head; while (tmp) { Node *n = tmp->next; while (n && n->data == tmp->data) { Node *toFree = n; n = n->next; free(toFree); } tmp->next = n; tmp = n; } return head; } Node* insert(Node *head,int data) { Node *p = (Node*)malloc(sizeof(Node)); p->data = data; p->next=NULL; if(head==NULL){ head=p; } else if(head->next==NULL) { head->next=p; } else{ Node *start=head; while(start->next!=NULL) start=start->next; start->next=p; } return head; } void display(Node *head) { Node *start=head; while(start) { printf("%d ",start->data); start=start->next; } } int main() { int T,data; scanf("%d",&T); Node *head=NULL; while(T-->0){ scanf("%d",&data); head=insert(head,data); } head=removeDuplicates(head); display(head); }
C
/* * 例8.22 * 用函数求整数 a 和 b 中的大者。 */ #include <stdio.h> int main() { int max(int, int); int (* p)(int, int); int a, b, c; p = max; printf("Please enter a and b:"); scanf("%d, %d", &a, &b); c = (* p)(a, b); printf("a = %d\nb = %d\nmax = %d\n", a, b, c); return 0; } int max(int a, int b) { return a > b ? a : b; }
C
#include <stdio.h> #include <stdlib.h> #include "main.h" #include "util.h" void generateCSV(char *filename) { int range = 100; int freqdist[range][2]; int maxval = 0, minval = 999; int freqminindex = 0; int freqmaxindex = 0; int i; FILE *fp; // Initialise the frequency distribution array for (i = 0; i < range; i++) { freqdist[i][0] = 0; freqdist[i][1] = 0; } // Find max and min value of the distribution for (i = 0; i < range; i++) { if(min_values[i] > maxval) { maxval = min_values[i]; } if (min_values[i] < minval) { minval = min_values[i]; } } // Add value in distribution for (i = 0; i < range; i++) { freqdist[i][0] = i; freqdist[i][1] = min_values[i]; } fp = fopen(filename, "w"); if (fp == NULL) { printf("Can't open output file %s!\n",filename); exit(1); } for (i = 0; i < range; i++) fprintf(fp, "%d,%d\n", freqdist[i][0], freqdist[i][1]); fclose(fp); } uint64_t analyze_times() { int i, j, count, maxcount=0; uint64_t max_dev = 0, min_time = 0, max_time = 0, temp, mostrepeatvar; uint64_t *temp_values; //find minimum and maximum deviation in a sample for (j=0; j<BOUND_OF_LOOP; j++) { max_dev = 0; min_time = 0; max_time = 0; for (i =0; i<SIZE_OF_STAT; i++) { //printf("%lu ",times[j][i]); if ((min_time == 0)||(min_time > times[j][i])) min_time = times[j][i]; if (max_time < times[j][i]) max_time = times[j][i]; } max_dev = max_time - min_time; min_values[j] = min_time; printf("sample no:%d\tmax_deviation: %lu\tmin clock cycle: %lu\n", j, max_dev, min_time); } //find most occuring minimum value temp_values = malloc(BOUND_OF_LOOP*sizeof(uint64_t)); if (!temp_values) { printf("unable to allocate memory for temp_values\n"); return 0; } for (j=0; j<BOUND_OF_LOOP; j++) { temp_values[j] = min_values[j]; } //sort the array for (i=0; i< (BOUND_OF_LOOP - 1); i++) { for (j=0; j< (BOUND_OF_LOOP - i - 1); j++) { if (temp_values[j] > temp_values[j+1]) { temp = temp_values[j]; temp_values[j] = temp_values[j+1]; temp_values[j+1] = temp; } } } //find the most repeated one for (i=0; i< BOUND_OF_LOOP ; i+=j-i) { count = 0; //printf("\ni= %d\n",i); for (j=i; j< BOUND_OF_LOOP; j++) { //printf("j= %d\n",j); if (temp_values[i] == temp_values[j]) count++; else break; } if (count > maxcount) { maxcount = count; mostrepeatvar = temp_values[i]; } } printf("\nMost repeated min clockcycles: %lu\tcount: %d\n",mostrepeatvar,maxcount); return mostrepeatvar; } uint64_t analyze_stimes() { int i, j, count, maxcount=0; uint64_t max_dev = 0, min_time = 0, max_time = 0, temp, mostrepeatvar; uint64_t *temp_values; //find minimum and maximum deviation in a sample for (j=0; j<BOUND_OF_LOOP; j++) { if ((min_time == 0)||(min_time > cstimes[j])) min_time = cstimes[j]; min_values[j] = cstimes[j]; printf("sample no:%d\tclock cycles: %lu\n", j, cstimes[j]); } printf("\nMinimum clock cycles: %lu\t\n",min_time); return min_time; }
C
/** * main - prints a line with system echo * Return: returns 1 */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(void) { write(2, "and that piece of art is useful\" \ - Dora Korpar, 2015-10-19\n", 59); return (1); }
C
#include <cstdio> #include <cstring> #include <vector> #include <algorithm> bool visited[8][8]; int y_direction[8] = {-2, -2, -1, -1, 1, 1, 2, 2}; int x_direction[8] = {-1, 1, 2, -2, 2, -2, -1, 1}; int record[64]; bool found; struct Node { int x, y, weight; Node(int x, int y, int weight) { this->x = x; this->y = y; this->weight = weight; } bool operator<(const Node &node) const { return weight < node.weight; } }; inline bool is_valid(int x, int y) { return x >= 0 && x < 8 && y >= 0 && y < 8; } inline int get_number(int x, int y) { return x * 8 + y + 1; } inline int get_weight(int x, int y) { int temp_x, temp_y, weight = 0; for (int i = 0; i < 8; i++) { temp_x = x + x_direction[i], temp_y = y + y_direction[i]; if (is_valid(temp_x, temp_y) && !visited[temp_x][temp_y]) weight++; } return weight; } void dfs(int x, int y, int step) { if (visited[x][y] || found) return; visited[x][y] = true; record[step] = get_number(x, y); if (step == 63) { found = true; return; } int temp_x, temp_y; std::vector<Node> v; for (int i = 0; i < 8; i++) { temp_x = x + x_direction[i], temp_y = y + y_direction[i]; if (is_valid(temp_x, temp_y) && !visited[temp_x][temp_y]) v.push_back(Node(temp_x, temp_y, get_weight(temp_x, temp_y))); } std::sort(v.begin(), v.end()); for (int i = 0; (size_t)i < v.size(); i++) dfs(v[i].x, v[i].y, step + 1); visited[x][y] = false; } int main() { int n; while (scanf("%d", &n) && n != -1) { found = false; memset(visited, 0, sizeof(visited)); dfs((n - 1) / 8, (n - 1) % 8, 0); for (int i = 0; i < 63; i++) printf("%d ", record[i]); printf("%d\n", record[63]); } return 0; }
C
/* ** EPITECH PROJECT, 2019 ** zappy ** File description: ** write epoll */ #include "AI.h" /*! ** @brief writing to server ** ** @param client just a storage ** @param str what to write ** @return int res of write */ int write_on_client(client_t *client, char *str) { int res; res = dprintf(client->fd, "%s\n", str); return (res); }
C
// // Created by Kevin Yu on 2016-05-20. // #ifndef FALTON_PHYSICSWINDOW_H #define FALTON_PHYSICSWINDOW_H #include <falton/collision/broadphase/ftHierarchicalGrid.h> #include <falton/collision/broadphase/ftDynamicBVH.h> #include <falton/collision/broadphase/ftToroidalGrid.h> #include <falton/collision/broadphase/ftQuadTree.h> #include <IMGUI/imgui.h> #include <IMGUI/imgui_internal.h> struct PhysicsConfigWindow { ftPhysicsSystem::ftConfig config; ftHierarchicalGrid::ftConfig hierarchicalConfig; ftDynamicBVH::ftConfig bvhConfig; ftToroidalGrid::ftConfig toroidalConfig; ftQuadTree::ftConfig quadConfig; enum Broadphase { NSquaredBroadphase, HierarchicalGrid, DynamicBVH, ToroidalGrid, QuadTree } broadphase; const char* windowTitle = "Physics Configuration"; const char* broadphaseNames[5] = {"NSquared Broadphase", "Hierarchical Grid", "Dynamic BVH", "ToroidalGrid", "QuadTree"}; void Draw() { ImGui::SetNextWindowSize(ImVec2(450,300), ImGuiSetCond_Once); ImGui::Begin(windowTitle); ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth() * 0.5f); ImGui::Text("General"); ImGui::InputFloat("Time to sleep", &config.sleepTimeLimit); ImGui::InputFloat("Linear sleep limit", &config.sleepLinearLimit); ImGui::InputFloat("Angular sleep limit", &config.sleepAngularLimit); ImGui::SliderFloat("Sleep Ratio", &config.sleepRatio, 0.0f, 1.0f, "%.3f"); ImGui::SliderFloat("Baumgarte Coefficient", &config.solverConfig.baumgarteCoef, 0.0f, 1.0f, "%.3f"); ImGui::SliderFloat("Allowed Penetration", &config.solverConfig.allowedPenetration, 0.0f, 1.0f, "%.3f"); ImGui::InputInt("Solver Iteration",(int*)&config.solverConfig.numIteration); ImGui::InputFloat2("Gravity",(float*)&config.gravity); ImGui::NewLine(); ImGui::Separator(); ImGui::Text("Broadphase"); ImGui::Combo("Broadphase", reinterpret_cast<int*>(&broadphase), broadphaseNames, IM_ARRAYSIZE(broadphaseNames)); switch (broadphase) { case HierarchicalGrid : { ImGui::InputInt("Number Of Level", (int *)&hierarchicalConfig.nLevel); ImGui::InputFloat("Base Size", &hierarchicalConfig.baseSize); ImGui::InputFloat("Size Multiplier",&hierarchicalConfig.sizeMul); ImGui::InputInt("Number Of Bucket", (int*)&hierarchicalConfig.nBucket); break; } case DynamicBVH : { ImGui::InputFloat("AABB Extension", &bvhConfig.aabbExtension); break; } case ToroidalGrid : { ImGui::InputFloat("Cell Size", &toroidalConfig.cellSize); ImGui::InputInt("nRow", (int*)&toroidalConfig.nRow); ImGui::InputInt("nColumn", (int*)&toroidalConfig.nCol); break; } case QuadTree : { ImGui::InputFloat2("min", (float*)&quadConfig.worldAABB.min); ImGui::InputFloat2("max", (float*)&quadConfig.worldAABB.max); ImGui::InputInt("Max Level", (int*)&quadConfig.maxLevel); break; } default : { break; } } ImGui::PopItemWidth(); ImGui::End(); } }; #endif //FALTON_PHYSICSWINDOW_H
C
/* -*- Mode: C; tab-width: 8; c-basic-offset: 2; indent-tabs-mode: nil; -*- */ #include "util.h" int main(void) { int sig; for (sig = 1; sig <= 64; ++sig) { struct sigaction sa; /* Skip signals that are fatal and can't be ignored, and skip signals that rr uses for itself. */ if (sig == SIGKILL || sig == SIGSTOP || sig == SIGSTKFLT || sig == SIGPWR) { continue; } sa.sa_handler = SIG_IGN; sa.sa_flags = 0; sa.sa_restorer = NULL; sigemptyset(&sa.sa_mask); /* Avoid libc wrappers since glibc won't let us send certain signals that it reserves for itself */ test_assert(0 == syscall(SYS_rt_sigaction, sig, &sa, (void*)0, 8)); test_assert(0 == kill(getpid(), sig)); } atomic_puts("EXIT-SUCCESS"); return 0; }
C
/* ************************************************************************** */ /* */ /* :::::::: */ /* ft_itoa_base_prec.c :+: :+: */ /* +:+ */ /* By: bmans <marvin@codam.nl> +#+ */ /* +#+ */ /* Created: 2020/01/13 15:36:04 by bmans #+# #+# */ /* Updated: 2020/06/25 14:00:08 by bmans ######## odam.nl */ /* */ /* ************************************************************************** */ #include "libftprintf.h" static u_int32_t ft_digitcount_base(u_int64_t n, u_int32_t base) { unsigned int digits; digits = 1; while (n > base - 1) { n = n / base; digits++; } return (digits); } char *ft_itoa_base_prec(u_int64_t n, char *basedigits, int prec) { char *a; u_int32_t digits; u_int32_t base; base = ft_strlen(basedigits); if (base < 2 || (prec == 0 && n == 0)) return (ft_strdup("")); digits = ft_digitcount_base(n, base); if (digits < (u_int32_t)prec && prec != -1) digits = prec; a = malloc(sizeof(char) * (digits + 1)); if (a) { a[digits] = '\0'; while (digits > 0) { digits--; a[digits] = basedigits[(u_int32_t)(n % base)]; n = (n / base); } } return (a); }
C
#include <stdio.h> int atoiCopy(char s[]); int main(void) { char str1[] = "-123"; printf("Result: %d", atoiCopy(str1)); return 0; } int atoiCopy(char s[]) { int result = 0; int i = 0; int p = 1; // Check if the number is negative and modify p if (s[0] == '-') { i = 1; p = -1; } for (; s[i] != '\0'; i++) { result = result * 10 + (s[i] - '0'); } result *= p; return result; }
C
#ifndef __HELPER_H__ #define __HELPER_H__ #include <inttypes.h> // Initializes array with random values dependent on given seed uint32_t *init_array(int size, int seed); // Prints array in desired format void print_array(uint32_t *arr, int size, int num_print); // Performs swap between two values in array // // *arr = pointer to array // index1 = first index to be swapped // index2 = second index to be swapped // moves = number of moves to be incremented by 3 // // Returns updated number of moves int swap(uint32_t *arr, int index1, int index2, int moves); #endif
C
//NOME: IGOR EIKI FERREIRA KUBOTA //RA: 19.02466-5 #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 80 #define N 10 typedef struct { char nome[MAX]; int idade; } Pessoa; void LerString(char []); void preencherVetor(Pessoa*, int); void exibirVetor(Pessoa*, int); int BuscaBinariaRecursiva(Pessoa[], Pessoa*, int, int); void quicksort(Pessoa*, int, int); int main() { int n; Pessoa listaDePessoas[N], perdido; printf("Digite o numero de pessoas: "); scanf("%i", &n); preencherVetor(listaDePessoas, n); quicksort(listaDePessoas, 0, n-1); exibirVetor(listaDePessoas, n); printf("Digite o nome da pessoa que deseja procurar: "); LerString(perdido.nome); if (BuscaBinariaRecursiva(listaDePessoas, &perdido, 0, n-1) != -1 ) printf("Idade: %i\n", perdido.idade); else printf("Pessoa nao cadastrada.\n"); return 0; } int BuscaBinariaRecursiva(Pessoa v[], Pessoa *p, int L, int H) { int pos = -1; return pos; } void preencherVetor(Pessoa *v, int n){ int i; for (i = 0; i < n; i++) { printf("Digite o nome: "); LerString(v[i].nome); printf("Digite a idade: "); scanf("%i", &v[i].idade); } } void exibirVetor(Pessoa *v, int n){ int i; printf("\n\nNome\tIdade\n"); for (i = 0; i < n; i++) printf("%s\t%i\n", v[i].nome, v[i].idade); printf("\n"); } void trocar(Pessoa *x, Pessoa *y){ } int particionar(Pessoa *v, int l, int r, int p){ int i, j; int valor_pivo = v[p]; trocar(&v[p], &v[r]); j = l; for (i = l; i <= r - 1; i++) { if (v[i] <= valor_pivo) { trocar(&v[i], &v[j]); j++; } } trocar(&v[j], &v[r]); return j; } void quicksort(Pessoa *v, int l, int r){ int pivo, novoPivo; /* se a lista possui 2 ou mais elementos */ if (l < r) { /* escolher o ndice do meio como piv */ pivo = (l + r) / 2; novoPivo = particionar(v, l, r, pivo); /* ordenao recursiva dos subvetores */ quicksort(v, l, novoPivo - 1); quicksort(v, novoPivo + 1, r); } } void LerString(char s[MAX]){ setbuf(stdin, 0); fgets(s, MAX, stdin); if (s[strlen(s)-1] == '\n') s[strlen(s)-1] = '\0'; }
C
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include <malloc.h> #include <stdlib.h> #pragma pack(1) typedef struct{ unsigned char B; unsigned char G; unsigned char R; }RGB; #define W 1440 #define H 900 void mzk(RGB (*buf)[W], int pos_x, int pos_y, int len) { RGB color = buf[pos_y][pos_x];//{.R=0xff}; int i,j; for(i=0; i<H; i++) { for(j=0; j<W; j++) { if( (i>=pos_y && i<= (pos_y+len) ) && (j>=pos_x && j<= (pos_x+len) ) ) buf[i][j] = color; } } } int main(int argc, char *argv[]) { if(2 != argc) { printf("Usage: %s <file>\n", argv[0]); return -1; } //open source int fds = open(argv[1], O_RDONLY); if(-1 == fds) { perror("open src file"); // return -1; exit(-1); } //create new file char destfile[20] = {0}; strcat(strcat(destfile, "mzk."), argv[1]); int fdd = open(destfile, O_WRONLY | O_CREAT | O_TRUNC, 0666); if(-1 == fdd) { perror("open des file"); return -1; } //copy BMP head char header[54]; read(fds, header, sizeof header); write(fdd, header, sizeof header); //read src RGB buf[H][W]; // lseek(fds, 54, SEEK_SET); int ret; ret = read(fds, buf, sizeof buf); mzk(buf, 500, 500, 100); write(fdd, buf, ret); //close src & new close(fds); close(fdd); }
C
#include <stdio.h> #include <stdlib.h> int main() { long int a,b,sum1,sum2,count; while(scanf("%ld%ld",&a,&b)==2){ sum1=0; sum2=0; count = 0; while(1){ sum1+=a; sum2+=b; count++; if((sum2-sum1)>=b){ break; } } printf("%ld\n",count); } return 0; }
C
/* * sigchldwait.c * * Created on: May 22, 2018 * Author: yifeifan */ #include "unp.h" void sig_chld(int signo) { pid_t pid; int stat; /* pid = wait(&stat); */ while((pid = waitpid(-1,&stat,WNOHANG)) > 0) printf("child %d terminated\n",pid); return; }
C
#include<stdio.h> #include<unistd.h> #include<stdlib.h> void test(void) { pid_t pid; pid = vfork(); if(pid == -1) { perror("vfork"); exit(EXIT_FAILURE); } else if(pid == 0) { printf("1:chaild pid = %d,ppid = %d\n",getpid(),getppid()); return; } else{ printf("2:parent pid = %d,ppid = %d\n",getpid(),getppid()); } } void fun(void) { int i; int buf[100]; for(i = 0;i < 100;++i) { buf[i] = 0; printf("3:child pid = %d,ppid = %d",getpid(),getppid()); } } int main() { pid_t pid; test(); fun(); return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/socket.h> #include <arpa/inet.h> #include <pthread.h> #include <unistd.h> #include <dirent.h> #include <sys/stat.h> #include <stdint.h> #include <signal.h> #include "aes.h" #define CBC 1 #define ECB 1 #define TRUE 1 #define FALSE 0 /* Fail Code */ #define SERVER_SOCKET_FAIL 1 #define SERVER_BIND_FAIL 2 #define PTHREAD_CREATE_FAIL 3 #define DEFAULT_PORT 8888 #define MAX_CLIENT 3 #define MAX_FILENAME_LEN 100 #define MAX_COMMAND_LEN 50 #define MAX_MESSAGE_LEN 4096 /* thansfer flags */ #define TRANSFER_WAIT 0 #define TRANSFER_OK 1 #define TRANSFER_DISCARD 2 struct node { int desc; int isTransfer; struct node *next; }*head; void message_trim(char*); void *connection_handler(void *); void *server_cmd_handler(); // linked list handle client sockets int client_cnt = 0; void append(int); void addBeginning(int); void addAfter(int, int); void insert(int); int delete(int); void setTransferFlag(int, int); void send2All(char *); // clear before exit void ShutDown(unsigned); void clean(); void intHandler(int sig); // DEBUG - CHECK THE HEX OF THE STRING // static void phex(uint8_t* str); int main(int argc , char *argv[]) { signal(SIGINT, intHandler); /* server's and client's file descriptor => -1 means error */ int ss_desc , cs_desc; struct sockaddr_in server , client; char *message; // Create socket ss_desc = socket(AF_INET , SOCK_STREAM , 0); // IPv4, TCP if (ss_desc == -1) { fprintf(stderr, "Fail to create server's socket"); return SERVER_SOCKET_FAIL; } // set reuse address => avoid TCP TIME_WAIT session /* Enable address reuse */ int on = 1; setsockopt( ss_desc, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on) ); /* Set port */ int port = DEFAULT_PORT; if(argc==2) port = atoi(argv[1]); else printf("Use default port: %d\n", DEFAULT_PORT); // Server socket info. sockaddr_in struct server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons( port ); // Bind if( bind(ss_desc, (struct sockaddr *)&server, sizeof(server)) < 0) { puts("bind failed"); return SERVER_BIND_FAIL; } puts("bind done"); // Create pthread for broadcast pthread_t thread; if( pthread_create( &thread , NULL , server_cmd_handler , NULL) < 0) { perror("Fail to create broadcast thread"); return PTHREAD_CREATE_FAIL; } // Listen. Accept at most MAX_CLIENT clients listen(ss_desc , MAX_CLIENT); // accept() to wait for new clients puts("Waiting for incoming connections..."); int structlen = sizeof(struct sockaddr_in); while( (cs_desc = accept(ss_desc, (struct sockaddr *)&client, (socklen_t*)&structlen)) ) { // DEBUG - CHECK CLIENT DESC // printf("Client %d connect!!\n", cs_desc); // Create pthread for each client pthread_t thread; int* param_desc = malloc(sizeof(int)); *param_desc = cs_desc; if( pthread_create( &thread , NULL , connection_handler , (void*) param_desc) < 0) { perror("Fail to create new pthread"); return PTHREAD_CREATE_FAIL; } } if (cs_desc<0) { perror("Accept failed"); return 1; } return 0; } /* Handle client's process */ void *connection_handler(void *socket_desc) { int sock = *(int*)socket_desc; size_t read_size; char *server_message , client_command[MAX_COMMAND_LEN], client_message[MAX_MESSAGE_LEN]; char filename[MAX_FILENAME_LEN]; // add client list client_cnt++; insert(sock); // Welcome message server_message = "#############################################\n"; write(sock , server_message , strlen(server_message)); server_message = "Welcome to Internet editor\n"; write(sock , server_message , strlen(server_message)); server_message = "#############################################\n"; write(sock , server_message , strlen(server_message)); // server_message = "There are some options you can choose below:\n"; // write(sock , server_message , strlen(server_message)); server_message = "1. create\n2. edit\n3. cat\n4. download (dl)\n5. list (ls)\n6. encrypt (en)\n7. decrypt (de)\n8. rename\n9. remove (rm)\n10. put\n11. alias <command> <alias>\n12. quit (bye)\n"; write(sock , server_message , strlen(server_message)); server_message = "#############################################\n\n"; write(sock , server_message , strlen(server_message)); // Get command from user and response while( (read_size = recv(sock , client_command , MAX_COMMAND_LEN-1 , 0)) > 0 ) { // DEBUG - CHECK RECEIVE COMMAND // printf("get command %s\n", client_command); // c => create new file if(strncmp(client_command, "create", 6) == 0) { server_message = "File name: "; write(sock, server_message, strlen(server_message)); if((read_size = recv(sock, filename, MAX_FILENAME_LEN-1, 0)) > 0) // get filename from client { /* check whether the file exists */ // BUG - IF FILE NAME IS EMPTY => CRASH if(filename[0]=='\n') { server_message = "File name can't be empty\n"; write(sock, server_message, strlen(server_message)); } else if(access(filename, F_OK) != -1) { server_message = "The file has already existed!\n"; write(sock, server_message, strlen(server_message)); } else { FILE* fp = fopen(filename, "w"); // create new file fclose(fp); fp = NULL; server_message = "Create successfully\n"; write(sock, server_message, strlen(server_message)); } } else perror("recv failed"); } // e => edit // BUG - GET GARBAGE POSTFIX CHAR AFTER OTHER COMMAND else if(strncmp(client_command, "edit", 4) == 0) { server_message = "File name: "; write(sock, server_message, strlen(server_message)); if((read_size = recv(sock, filename, MAX_FILENAME_LEN-1, 0)) > 0) // get filename from client { if(access(filename, F_OK) != -1) { server_message = "Stop and save by `EOF` in a line.\n"; write(sock, server_message, strlen(server_message)); FILE* fp = fopen(filename, "a+"); if(fp) { while((read_size = recv(sock, client_message, MAX_MESSAGE_LEN-1, 0)) > 0) { client_message[read_size] = '\n'; client_message[read_size+1] = '\0'; if(strcmp(client_message, "`EOF`\n") == 0) break; // printf("get message: %s\n", client_message); fprintf(fp, "%s", client_message); fflush(fp); } server_message = "Saved!!\n"; write(sock, server_message, strlen(server_message)); } else fprintf(stderr, "Fail to open the file\n"); } else { server_message = "File doesn't exist\n"; write(sock, server_message, strlen(server_message)); } } else perror("recv failed"); } // cat else if(strncmp(client_command, "cat", 3) == 0) { server_message = "File name: "; write(sock, server_message, strlen(server_message)); if((read_size = recv(sock, filename, MAX_FILENAME_LEN-1, 0)) > 0) // get filename from client { if(access(filename, F_OK) != -1) { FILE* fp = fopen(filename, "r"); char segment[MAX_MESSAGE_LEN]; while(fgets(segment, MAX_MESSAGE_LEN, fp)) { segment[strlen(segment)] = '\0'; write(sock, segment, strlen(segment)); } } else { server_message = "File doesn't exist\n"; write(sock, server_message, strlen(server_message)); } } else perror("recv failed"); } // r => remove else if(!(strncmp(client_command, "remove", 6)&&strncmp(client_command, "rm", 2))) { server_message = "File name: "; write(sock, server_message, strlen(server_message)); if((read_size = recv(sock, filename, MAX_FILENAME_LEN-1, 0)) > 0) // get filename from client { if(access(filename, F_OK) != -1) { remove(filename); } else { server_message = "File doesn't exist\n"; write(sock, server_message, strlen(server_message)); } } else perror("recv failed"); } // l => list directory else if(!(strncmp(client_command, "list", 4)&&strncmp(client_command, "ls", 2))) { struct dirent **namelist; int n; // assign "current" files to namelist and sort by alphasort without filter. n = scandir(".", &namelist, NULL, alphasort); if(n<0) perror("scandir error"); else { int i; for(i=0; i<n; i++) { write(sock, namelist[i]->d_name, strlen(namelist[i]->d_name)); write(sock, " ", 1); free(namelist[i]); } write(sock, "\n", 1); } } // d => download /* 1. Normal send data * 2. Target file doesn't exist => discard * 3. Client doesn't allow to overwrite data => discard */ else if(!(strncmp(client_command, "download", 8)&&strncmp(client_command, "dl", 2))) { /* ask downloaded filename */ server_message = "File name: "; write(sock, server_message, strlen(server_message)); if((read_size = recv(sock, filename, MAX_FILENAME_LEN-1, 0)) > 0) // get filename from client { // DEBUG - CHECK TRIMED FILE NAME SENDED BY CLIENT // printf("%s\n", filename); uint8_t segment[MAX_MESSAGE_LEN]; if(access(filename, F_OK) != -1) { /* send file's size */ struct stat st; int result = stat(filename, &st); long long fsize = st.st_size; sprintf(segment, "%lld", fsize); // printf("convert file size = %s\n", segment); write(sock, segment, strlen(segment)); /* Wait for TRANSFER signal */ int transfer_flag = TRANSFER_WAIT; while(transfer_flag == TRANSFER_WAIT) { // printf("start wait\n"); if((read_size = recv(sock, client_message, MAX_MESSAGE_LEN-1, 0)) > 0) { client_message[read_size] = '\0'; if(strcmp(client_message, "TRANSFER_OK") == 0) transfer_flag = TRANSFER_OK; else if(strcmp(client_message, "TRANSFER_DISCARD") == 0) transfer_flag = TRANSFER_DISCARD; } else if(read_size == -1) perror("tranfer flag recv failed"); else if(read_size == 0) break; // printf("trans_state = %d\n", transfer_flag); } if(transfer_flag == TRANSFER_OK) { setTransferFlag(sock, TRUE); // puts("ready to send the data"); /* Start transfer data */ FILE* fp = fopen(filename, "r"); while(read_size = fread(segment, sizeof(uint8_t), MAX_MESSAGE_LEN-1, fp)) { write(sock, segment, read_size); // tranfer data to client until EOF } setTransferFlag(sock, FALSE); } } else { server_message = "FILE_NOT_EXIST"; // transfer flag write(sock, server_message, strlen(server_message)); } } else perror("recv failed"); } // Client transfer file else if(!strncmp(client_command, "put", 3)) { int trans_state; if((read_size = recv(sock, client_message, MAX_MESSAGE_LEN-1, 0)) > 0) // Get file name and size { // Parse client exist, filename and file size by '/' char *tok; tok = strtok(client_message, "/"); if(!strncmp(tok, "FILE_EXIST", 10)) { tok = strtok(NULL, "/"); strcpy(filename, tok); tok = strtok(NULL, "/"); long long filesize; filesize = atoll(tok); // printf("get %s %lld\n", filename, filesize); // Check file existence if(access(filename, F_OK)!=-1) { write(sock, "TRANSFER_WAIT", 13); trans_state = TRANSFER_WAIT; } else { write(sock, "TRANSFER_OK", 11); trans_state = TRANSFER_OK; } // Wait and get overwrite flag if(trans_state == TRANSFER_WAIT) { recv(sock, client_message, MAX_MESSAGE_LEN-1, 0); if(!strncmp(client_message, "TRANSFER_DISCARD", 16)) trans_state = TRANSFER_DISCARD; else trans_state = TRANSFER_OK; // send ready flag write(sock, "READY", 5); } // recv if(trans_state == TRANSFER_OK) { setTransferFlag(sock, TRUE); FILE *fp = fopen(filename, "w"); long long receive_cnt = 0; /* start to receive data */ uint8_t segment[MAX_MESSAGE_LEN]; while(receive_cnt < filesize) { read_size= recv(sock, segment, MAX_MESSAGE_LEN-1, 0); receive_cnt += read_size; fwrite(segment, sizeof(uint8_t), read_size, fp); fflush(fp); } printf("Get \"%s\" from client\n", filename); fclose(fp); fp = NULL; setTransferFlag(sock, FALSE); } } } else perror("recv failed"); } // AES128 ECB encrypt else if(!(strncmp(client_command, "encrypt", 7)&&strncmp(client_command, "en", 2))) { server_message = "File name: "; write(sock, server_message, strlen(server_message)); if((read_size = recv(sock, filename, MAX_FILENAME_LEN-1, 0)) > 0) // get filename from client { /* concat .cip ext */ const uint8_t ext[] = ".cip"; char tempfilename[MAX_FILENAME_LEN]; strcpy(tempfilename, filename); int namelen = strlen(filename); strncpy(tempfilename+namelen, ext, 5); // DEBUG - CHECK EXT FILENAME // printf("%s %s\n", filename, tempfilename); if(access(filename, F_OK) != -1) { /* ask client for 16 bytes password */ server_message = "Password <= 16 letters: "; write(sock, server_message, strlen(server_message)); uint8_t key[16]; if((read_size = recv(sock, client_message, MAX_MESSAGE_LEN-1, 0)) > 0) { /* discard letter if the length is more than 16 */ strncpy(key, client_message, 16); // printf("key length = %zu\n", strlen(client_message)); if(strlen(client_message) > 16+1) { server_message = "Key too long.\nThe letters longer than 16 will be discarded.\n"; write(sock, server_message, strlen(server_message)); } FILE *pfp = fopen(filename, "r"); FILE *cfp = fopen(tempfilename, "w"); const segment_size = 16; uint8_t in[segment_size]; uint8_t out[segment_size]; /* write file size */ uint64_t fsize; struct stat st; int result = stat(filename, &st); fsize = st.st_size; fwrite(&fsize, sizeof(uint64_t), 1, cfp); /* write contents */ while(read_size = fread(in, sizeof(uint8_t), segment_size, pfp)) { AES128_ECB_encrypt(in, key, out); // DEBUG - CHECK DECRYPT // printf("Plain text: \n"); // phex(in); // phex(out); // AES128_ECB_decrypt(out, key, rec); // phex(rec); fwrite(out, sizeof(uint8_t), 16, cfp); } remove(filename); rename(tempfilename, filename); fclose(pfp); pfp = NULL; fclose(cfp); cfp = NULL; } else perror("Fail to get key"); } else { server_message = "File doesn't exist\n"; write(sock, server_message, strlen(server_message)); } } else perror("recv failed"); } // decrypt // AES128 ECB encrypt else if(!(strncmp(client_command, "decrypt", 7)&&strncmp(client_command, "de", 2))) { server_message = "File name: "; write(sock, server_message, strlen(server_message)); if((read_size = recv(sock, filename, MAX_FILENAME_LEN-1, 0)) > 0) // get filename from client { /* discard .cip ext */ const char ext[] = ".rec"; char tempfilename[MAX_FILENAME_LEN]; strcpy(tempfilename, filename); int namelen = strlen(filename); strncpy(tempfilename+namelen, ext, 5); // DEBUG - CHECK EXT FILENAME // printf("%s %s\n", filename, tempfilename); if(access(filename, F_OK) != -1) { /* ask client for 16 bytes password */ server_message = "Password <= 16 letters: "; write(sock, server_message, strlen(server_message)); uint8_t key[16]; if((read_size = recv(sock, client_message, MAX_MESSAGE_LEN-1, 0)) > 0) { /* discard letter if the length is more than 16 */ strncpy(key, client_message, 16); if(strlen(client_message) > 16+1) { server_message = "Key too long.\nThe letters longer than 16 will be discarded.\n"; write(sock, server_message, strlen(server_message)); } FILE *cfp = fopen(filename, "rb"); FILE *rfp = fopen(tempfilename, "wb"); const segment_size = 16; uint8_t in[segment_size]; uint8_t out[segment_size]; /* get file size */ uint64_t fsize; fread(&fsize, sizeof(uint64_t), 1, cfp); // printf("file size = %lld\n", fsize); uint64_t times = fsize/segment_size+1; // printf("times = %lld\n", times); int remainer = fsize-(times-1)*segment_size; // printf("remainer = %d\n", remainer); while(times--) { read_size = fread(in, sizeof(uint8_t), segment_size, cfp); AES128_ECB_decrypt(in, key, out); if(times) fwrite(out, sizeof(uint8_t), read_size, rfp); else fwrite(out, sizeof(uint8_t), remainer, rfp); } remove(filename); rename(tempfilename, filename); fclose(cfp); cfp = NULL; fclose(rfp); rfp = NULL; } else perror("Fail to get key"); } else { server_message = "File doesn't exist\n"; write(sock, server_message, strlen(server_message)); } } else perror("recv failed"); } // rename else if(strncmp(client_command, "rename", 6) == 0) { server_message = "Old and New file name. (Seperate by a blank)\n"; write(sock, server_message, strlen(server_message)); if((read_size = recv(sock, client_message, MAX_MESSAGE_LEN-1, 0)) > 0) // get filename from client { char newfilename[MAX_FILENAME_LEN]; sscanf(client_message, "%s %s", filename, newfilename); // DEBUG - CHEKC OLD AND NEW FILE NAME // printf("checking\n"); // printf("%s %s\n", filename, newfilename); if(access(filename, F_OK) != -1) { if(rename(filename, newfilename) == 0) server_message = "Successfully\n"; else server_message = "Fail\n"; write(sock, server_message, strlen(server_message)); } else { server_message = "File doesn't exist\n"; write(sock, server_message, strlen(server_message)); } } else perror("recv failed"); } // q => quit else if(!(strncmp(client_command, "quit", 4)&&strncmp(client_command, "bye", 3))) { server_message = "Bye Bye\n"; write(sock, server_message, strlen(server_message)); break; } else { server_message = "No such command\n"; write(sock, server_message, strlen(server_message)); } memset(filename, 0, sizeof(filename)); // prevent garbage character memset(client_command, 0, sizeof(client_command)); memset(client_message, 0, sizeof(client_message)); } if(read_size == 0) { // printf("Client %d disconnected\n", sock); // fflush(stdout); } else if(read_size == -1) { // perror("recv failed"); } close(sock); /* delete client list */ delete(sock); client_cnt--; /* Free private socket_desc */ free(socket_desc); return 0; } void *server_cmd_handler() { /* Server welcome message */ puts("#############################################"); puts("1. broadcast (bc)"); puts("2. showip (si)"); puts("3. shutdown [sec] (sd)"); puts("#############################################"); puts(""); char message[MAX_MESSAGE_LEN], command[MAX_COMMAND_LEN]; while(1) { fgets(command, MAX_COMMAND_LEN-1, stdin); if(command[0]=='\n') continue; message_trim(command); // broadcast. If client is downloading then not receive if(!(strncmp(command, "bc", 2)&&strncmp(command, "broadcast", 9))) { printf("Message: \n"); fgets(message, MAX_MESSAGE_LEN-1, stdin); message[strlen(message)] = '\0'; send2All(message); } else if(!(strncmp(command, "shutdown", 8)&&strncmp(command, "sd", 2))) { char dummy[8]; unsigned t; if(sscanf(command, "%s %u", dummy, &t)==2) { sprintf(message, "Notice: Server Will shutdown after %u seconds\n", t); send2All(message); ShutDown(t); } else { t = 10; printf("Shutdown server after %u seconds?[y/n] ", t); char check; do { scanf("%c", &check); } while(check!='n'&&check!='y'); if(check=='y') ShutDown(t); } } else if(!(strncmp(command, "showip", 6)&&strncmp(command, "si", 2))) { socklen_t len; struct sockaddr_storage addr; char ipstr[INET_ADDRSTRLEN]; int port; struct sockaddr_in *s; struct node *temp = head; // BUG - MUST GET FIRST FOR GARBAGE if(temp!=NULL) getpeername(temp->desc, (struct sockaddr*)&addr, &len); while(temp!=NULL) { getpeername(temp->desc, (struct sockaddr*)&addr, &len); s = (struct sockaddr_in *)&addr; port = ntohs(s->sin_port); inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof ipstr); printf("%s:%d\n", ipstr, port); temp = temp->next; } } else printf("No such command\n"); } } void send2All(char *message) { struct node* temp = head; while(temp!=NULL) { if(!temp->isTransfer) write(temp->desc, message, strlen(message)); temp = temp->next; } } void ShutDown(unsigned t) { while(t) { // count down if(t<=10) { printf("%u ", t); fflush(stdout); } t--; sleep(1); } puts(""); clean(head); exit(0); } /* remove trailing newline character */ void message_trim(char* msg) { int len = strlen(msg); msg[len-1] = '\0'; } // static void phex(uint8_t* str) // { // // original // unsigned char i; // for(i = 0; i < 16; ++i) // printf("%.2x ", str[i]); // printf("\n"); // } void setTransferFlag(int desc, int flag) { int cnt = 0; struct node *temp; temp = head; if(temp == NULL) return; else { while(temp!=NULL) { if(temp->desc==desc) { temp->isTransfer = flag; return; } else temp = temp->next; } } } void append(int desc) { struct node *temp,*right; /* create new node */ temp = (struct node *)malloc(sizeof(struct node)); temp->desc = desc; temp->isTransfer = FALSE; /* move to the end */ right=(struct node *)head; while(right->next != NULL) right=right->next; right->next = temp; temp->next = NULL; } void addBeginning(int desc) { struct node *temp; temp = (struct node *)malloc(sizeof(struct node)); temp->desc = desc; temp->isTransfer = FALSE; if(head == NULL) { head = temp; head->next = NULL; } else { temp->next = head; head = temp; } } void addAfter(int desc, int loc) { int i; struct node *temp,*left,*right; right=head; for(i=1;i<loc;i++) { left=right; right=right->next; } temp=(struct node *)malloc(sizeof(struct node)); temp->desc=desc; temp->isTransfer = FALSE; left->next=temp; left=temp; left->next=right; return; } void insert(int desc) { int cnt = 0; struct node *temp; temp = head; if(temp == NULL) addBeginning(desc); else { while(temp!=NULL) { if(temp->desc<desc) cnt++; temp=temp->next; } if(cnt==0) addBeginning(desc); else if(cnt<client_cnt) addAfter(desc,++cnt); else append(desc); } client_cnt++; } // return whether the element exist int delete(int desc) { struct node *temp, *prev; temp = head; while(temp!=NULL) { if(temp->desc==desc) { if(temp==head) { head=temp->next; free(temp); client_cnt--; return 1; } else { prev->next=temp->next; free(temp); client_cnt--; return 1; } } else { prev=temp; temp= temp->next; } } return 0; } void clean(struct node* cur) { if(cur==NULL) { client_cnt = 0; head = NULL; return; } clean(cur->next); close(cur->desc); free(cur); } void intHandler(int sig) { clean(head); exit(0); }
C
#include<stdio.h> #include<math.h> int main(){ int T,i,num; scanf("%d",&T); int tree[2048]={0}; int position[2048]={1}; int MAX=pow(2,T); scanf("%d",&tree[0]); while(T-->1){ scanf("%d",&num); for(i=0;i<MAX;i++) if(num<=tree[i]) if(position[2*i+1]){ i=2*i; continue; } else{ tree[2*i+1]=num; position[2*i+1]=1; break; } else if(position[2*i+2]){ i=2*i+1; continue; } else{ tree[2*i+2]=num; position[2*i+2]=1; break; } } for(i=0;i<MAX;i++) if(position[i]) printf("%d\n",tree[i]); return 0; }
C
#include <stdio.h> int main (void){ printf("Hello, dad!"); // dad answer print("\n- Hello, daughter!\n"); print("\n- How are you?\n"); print("\n- Good luck!\n"); return 0;}
C
/* * utils.c * * Created on: 9 Oct 2017 * Author: yunwu */ #include "utils.h" void InitializeRandoms() { // srand(4711); srand(time(NULL)); } int RandomEqualINT(int Low, int High) { return rand() % (High-Low+1) + Low; } float RandomEqualFLOAT(float Low, float High) { return ((float) rand() / RAND_MAX) * (High-Low) + Low; } void random_vector_float_factor(float *x, int size, float factor){ int i; for(i=0;i<size;i++){ x[i] = factor*RAND_MUL*(rand()%RAND_DIV)/RAND_DIV; } } void random_vector_float(float *x, int size){ int i; for(i=0;i<size;i++){ x[i] = (float)RAND_MUL*(float)(rand()%RAND_DIV)/RAND_DIV; } } void vector_add_float(float *a, float *b, float *c, int size){ int i; for(i=0;i<size;i++){ c[i] = a[i] + b[i]; } } void vector_sub_float(float *a, float *b, float *c, int size){ int i; for(i=0;i<size;i++){ c[i] = a[i] - b[i]; } } float vector_sum_float(float *a, int size){ int i; float sum = 0; for(i=0;i<size;i++){ sum += a[i]; } return sum; } void linear_vector_float(float *vec, int size){ int i=0; for(i=0;i<size;i++){ vec[i] = i; } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* aff_z.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dodoTheHacker <dodendaa@student.wethink +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/02/10 19:46:44 by dodoTheHack #+# #+# */ /* Updated: 2021/02/11 07:25:54 by dodoTheHack ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> void ft_putchar(char c) { write(1, &c, 1); } /* * Function: aff_z * -------------------- * displays the first 'z' character it encounters in it * * returns: void, aff_z prints 'z' followed by a newline on successfully finding * the char 'z' in a given string. If 'z' does not exist in the given string * only a newline character is printed * */ void aff_z(int argc, char **argv) { int index; index = 0; if (argc != 2) { ft_putchar('z'); ft_putchar('\n'); return ; } while(argv[1][index] != '\0') { if(argv[1][index] == 'z') { ft_putchar('z'); break; } index++; } ft_putchar('\n'); return ; } int main(int argc, char **argv) { aff_z(argc, argv); return (0); }
C
#include <stdio.h> #include <stdlib.h> #include <stdio.h> #include <stdlib.h> // prototipo /** \brief devuelve la suma de los parametros * * \param a int primer valor a sumar * \param b int segundo valor asumar * \return int la suma de los parametros * */ int sumar(); int main() { printf("La suma es %d\n", sumar()); return 0; } int sumar() { int x; int y; printf("Ingrese un numero: "); scanf("%d", &x); printf("Ingrese otro numero: "); scanf("%d", &y); return x + y; } /* void saludar(); int main() { saludar(); return 0; } void saludar() { printf("Hell world!\n"); }*/
C
#include <stdio.h> #include <stdlib.h> #include "funciones.h" #define TAMUSUARIO 100 #define TAMPRODUCTO 1000 int main() { int opcion; eUsuario listaDeUsuarios[TAMUSUARIO]; eProducto listaDeProductos[TAMPRODUCTO]; inicializarUsario(listaDeUsuarios, TAMUSUARIO); inicializarUsuariosHardCode(listaDeUsuarios, TAMUSUARIO); inicializarProductos(listaDeProductos, TAMPRODUCTO); inicializarProductosHardCode(listaDeProductos, TAMPRODUCTO); do { printf("\n1.ALTAS\n2.MODIFICACIONES\n3.BAJAS\n4.PUBLICAR PRODUCTO\n5.MODIFICAR PUBLICACION\n6.CANCELAR PUBLICACION\n7.COMPRAR PRODUCTO\n8.LISTAR PUBLICACIONES DEL USUARIO\n9.LISTAR PUBLICACIONES\n10.LISTAR USUARIOS\n11.SALIR\n \nElija una opcion: "); scanf("%d", &opcion); printf(" \n"); switch (opcion) { case 1: altaUsuario(listaDeUsuarios, TAMUSUARIO); mostrarUsuarios(listaDeUsuarios, TAMUSUARIO); break; case 2: modificarUsuario(listaDeUsuarios, TAMUSUARIO); mostrarUsuarios(listaDeUsuarios, TAMUSUARIO); break; case 3: bajaUsuario(listaDeUsuarios, TAMUSUARIO); mostrarUsuarios(listaDeUsuarios, TAMUSUARIO); break; case 4: altaProducto(listaDeProductos, TAMPRODUCTO); break; case 5: modificarProductos(listaDeProductos, TAMPRODUCTO); break; case 6: cancelarPublicacion(listaDeProductos, TAMPRODUCTO); break; case 7: comprarProducto(listaDeProductos, TAMPRODUCTO, listaDeUsuarios, TAMUSUARIO); break; case 8: mostrarProductosDelUsuario(listaDeProductos, TAMPRODUCTO); break; case 9: mostrarProductos(listaDeProductos, TAMPRODUCTO); break; case 10: listarUsuarios(listaDeUsuarios, TAMUSUARIO); break; } } while (opcion!=11); return 0; }
C
#include "mils.h" int mils(char* nombre) { struct dirent* entradadirectorio; DIR* directorio; if((directorio=opendir(nombre))==NULL) { fprintf(stderr,"\aNo pude abrir el directorio %s", nombre); perror("\n"); return(-1); } while(entradadirectorio=readdir(directorio)) { if(entradadirectorio -> d_ino!=0) { printf("%s\n",entradadirectorio->d_name); } } if(closedir(directorio)==-1) { fprintf(stderr,"\aNo pude cerrar el directorio %s",nombre); perror("\n"); return(-1); } return(0); }
C
//Roulette Game #include <stdio.h> #include <stdlib.h> #include <time.h> void showInstructions(); float getBetAmount(); void makeBet(int *, int *); int spinWheel(); float figureWinnings(int *, int *, float, int); int main() { char replay; int betType, bet, spin; float betAmount, winnings; showInstructions(); do{ makeBet(&betType, &bet); betAmount=getBetAmount(); spin=spinWheel(); winnings = figureWinnings(&betType, &bet, betAmount, spin); printf("The number spun is: %d\n", spin); if(winnings > 0){ printf("YOU WON %.2f DOLLARS!!!\n", winnings); }else{ winnings= winnings * -1; printf("YOU lost %.2f DOLLARS!!!\n", winnings); } printf("\n\nPress 'Y' To Play Again\n"); printf("Press Any Character To Quit\n"); scanf(" %c", &replay); } while (replay == 'Y' || replay == 'y'); printf("Thank You for playing\n"); return 0; } void showInstructions() { printf("The roulette wheel has the numbers 0-36 on it.\n"); printf("You can place your bet in one of three ways\n"); printf("\t\t1. Bet on a number (payout is 36 times the bet amount)\n"); printf("\t\t2. Bet on an odd or even (payout is 2 times the bet)\n"); printf("\t\t3. Bet on a dozen ~ first 1-12, second, 13-24, third 25-36 (payout is 3 times the bet)\n"); printf("The number zero does not count for odd or even or dozen, but can count as a number bet\n\n"); } void makeBet(int *betType, int *bet) { *betType = 0; *bet = -1; while(*betType != 1 && *betType != 2 && *betType != 3 ) { printf("What type of bet would you like to place?\n"); printf("1= Bet on a number\n"); printf("2= Bet on an odd or even\n"); printf("3= Bet on a dozen\n"); printf("Please Pick a number (1-3): "); scanf("%d", betType); } if(*betType == 1){ while(*bet < 0 || *bet > 36){ printf("What number do you bet on?\n"); printf("Please enter the number you bet on (0-36): "); scanf("%d", bet); } } else if(*betType == 2){ while(*bet != 1 && *bet != 2){ printf("What parity do you bet on?\n"); printf("1= Odd \n"); printf("2= Even \n"); scanf("%d", bet); } } else if(*betType == 3){ while(*bet != 1 && *bet!= 2 && *bet != 3 ){ printf("Which dozen do you bet on?"); printf("1= First dozen (1-12)"); printf("2= Second dozen (13-24)"); printf("3= Third dozen (25-36)"); scanf("%d", bet); } } } float getBetAmount() { float betAmount=0.0; while(betAmount <= 0){ printf("How much would you like to bet? $"); scanf("%f", &betAmount); } return betAmount; } int spinWheel() { srand(time(0)); return rand() % 37; } float figureWinnings(int *betType, int *bet, float betAmount, int actualOutcome){ float result = 0.0; if(*betType == 1){ if(*bet == actualOutcome){ result = 36.0 * betAmount; } else{ result = -1.0 * betAmount; } } else if(*betType == 2){ if((*bet == 1 && actualOutcome%2 == 1) || (*bet == 2 && actualOutcome%2 == 0 && actualOutcome != 0)){ result = 2.0 * betAmount; } else { result = -1.0 * betAmount; } } else if(*betType == 3){ if((*bet == 1 && actualOutcome>=1 && actualOutcome<=12) || (*bet == 2 && actualOutcome>=13 && actualOutcome<=24) || (*bet == 3 && actualOutcome>=25 && actualOutcome<=36)){ result = 3 * betAmount; } else { result = -1.0 * betAmount; } } return result; }
C
#include <stdlib.h> #include <stdio.h> void main(int argc, char* argv[]) { FILE *source = fopen(argv[1], "r"); FILE *dump = fopen(argv[2], "w"); char c; for (c = fgetc(source); c != EOF; c = fgetc(source)) if (((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c == '\n')) && c != 'x') fprintf(dump, "%c", c); else if (c == '/') { while ((c = fgetc(source)) != '\n') 1; fprintf(dump, "\n"); } fclose(source); fclose(dump); }
C
/* * Copyright (c) 2012-2013, chunquedong * * This file is part of fancpp project * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE version 3.0 * * History: * 2013-1-20 Jed Young Creation */ #ifndef _CF_BLOCKQUEUE_H_ #define _CF_BLOCKQUEUE_H_ #include "cfan/Queue.h" #include "tinyCThread/tinycthread.h" #include <stdio.h> CF_BEGIN /** * Blocking queue is a FIFO sequence. * Blocking when add to full queue or delete from empty queue. * It's like Golang channel. * This class is thread safe. * */ typedef struct cf_BlockingQueue_ { cf_Queue queue; mtx_t mutex; cnd_t addCond; cnd_t deleteCond; bool cancelAdd; bool cancelDelete; void (*onRemove)(void *); } cf_BlockingQueue; typedef enum cf_BlockingStrategy_ { cf_BlockingStrategy_donothing, cf_BlockingStrategy_blocking, cf_BlockingStrategy_removeLast, cf_BlockingStrategy_removeFirst } cf_BlockingStrategy; /** * constructor * */ cf_Error cf_BlockingQueue_make(cf_BlockingQueue *self, size_t capacity, unsigned int elemSize); /** * current num of elements */ static inline size_t cf_BlockingQueue_size(cf_BlockingQueue *self) { register size_t size; mtx_lock(&self->mutex); size = cf_Queue_size(&self->queue); mtx_unlock(&self->mutex); return size; } /** * queue is empty */ static inline bool cf_BlockingQueue_isEmpty(cf_BlockingQueue *self) { register bool result; mtx_lock(&self->mutex); result = cf_Queue_isEmpty(&self->queue); mtx_unlock(&self->mutex); return result; } /** * push element to back. * If block arg is true and queue is full will be blocked. */ cf_Error cf_BlockingQueue_add(cf_BlockingQueue *self, void *elem, cf_BlockingStrategy strate); /** * Release all blocked thread. */ static inline void cf_BlockingQueue_cancel(cf_BlockingQueue *self) { mtx_lock(&self->mutex); self->cancelAdd = true; self->cancelDelete = true; cnd_broadcast(&self->addCond); cnd_broadcast(&self->deleteCond); mtx_unlock(&self->mutex); } /** * pop out a front element. * If queue is empty will be blocked. */ void *cf_BlockingQueue_delete(cf_BlockingQueue *self); /** * clear and return last * If queue is empty will be blocked. */ void *cf_BlockingQueue_getAndClear(cf_BlockingQueue *self); /** * get first element but pop out. */ static inline void *cf_BlockingQueue_peek(cf_BlockingQueue *self) { register void *result; mtx_lock(&self->mutex); result = cf_Queue_peek(&self->queue); mtx_unlock(&self->mutex); return result; } /** * Destroy queue. * Must guarantee call cf_BlockingQueue_cancel before. */ static inline void cf_BlockingQueue_dispose(cf_BlockingQueue *self) { //cf_BlockingQueue_cancel(self); mtx_destroy(&self->mutex); cnd_destroy(&self->addCond); cnd_destroy(&self->deleteCond); cf_Queue_dispose(&self->queue); //printf("queue disposed\n"); } CF_END #endif
C
#include <stdio.h> #include <string.h> int main() { int loop1, loop2; char str1[81] = "AAA"; char str2[81] = "BBBB"; loop1 = strlen(str1); loop2 = 0; do { str1[loop1] = str2[loop2]; loop1++; loop2++; } while (str2[loop2] != '\0'); printf("str1:[%s]\n", str1); return 0; }
C
#include "des_utils.h" #include <stdio.h> /* Travis Machacek John Flickinger This is where we perform most of our bit manipulation operations. */ //check to see if bit is set int isNthBitSet (unsigned char c, int n) { static unsigned char mask[] = {128, 64, 32, 16, 8, 4, 2, 1}; return ((c & mask[n]) != 0); } /** * @brief exclusive-or two byte arrays and place output in array1. Only works if array 2 is longer or * of equal size to array 1. * @param arr1, first array * @param arr2, sencond array */ void xOrTwoByteArrays(unsigned char arr1[], unsigned char arr2[], int size1, int size2) { if(size2 < size1) { printf("error"); return; } int i; for(i = 0; i < size1; i++) { arr1[i] ^= arr2[i]; } } //function to look up positions from sbox void sBoxLookup(unsigned char * sOutput, unsigned char * b) { int i, j; for(i = 0; i < 8; i++) { int row, col; int in0, in1; int colin[4]; int cin0, cin1, cin2, cin3; row = col = 0x00; // in0 = (b[i] >> 5) & 0x01; // first if(isNthBitSet(b[i], 0)) { in0 = 1; } else { in0 = 0; } // in1 = (b[i] >> 0) & 0x01; // second if(isNthBitSet(b[i], 5)) { in1 = 1; } else { in1 = 0; } //middle 4 bits if(isNthBitSet(b[i], 1)) { cin0 = 1; } else { cin0 = 0; } if(isNthBitSet(b[i], 2)) { cin1 = 1; } else { cin1 = 0; } if(isNthBitSet(b[i], 3)) { cin2 = 1; } else { cin2 = 0; } if(isNthBitSet(b[i], 4)) { cin3 = 1; } else { cin3 = 0; } row ^= (-(in0) ^ row) & (1 << 1); row ^= (-(in1) ^ row) & (1 << 0); col ^= (-(cin0) ^ col) & (1 << 3); col ^= (-(cin1) ^ col) & (1 << 2); col ^= (-(cin2) ^ col) & (1 << 1); col ^= (-(cin3) ^ col) & (1 << 0); if(row == 0) { sOutput[i] = SBOXMAP[i][col]; sOutput[i] = sOutput[i] << 4; // printf("row: %d col: %d soutput: %d\n", row, col, sOutput[i]); } if(row == 1) { sOutput[i] = SBOXMAP[i][col + 16]; sOutput[i] = sOutput[i] << 4; // printf("row: %d col: %d soutput: %d\n", row, col, sOutput[i]); } if(row == 2) { sOutput[i] = SBOXMAP[i][col + 32]; sOutput[i] = sOutput[i] << 4; // printf("row: %d col: %d soutput: %d\n", row, col, sOutput[i]); } if(row == 3) { sOutput[i] = SBOXMAP[i][col + 48]; sOutput[i] = sOutput[i] << 4; // printf("row: %d col: %d soutput: %d\n", row, col, sOutput[i]); } } // end for } // end SboxLookup
C
#include <stdio.h> /* print array */ void print(int a[], int n) { int i; for(i = 0; i < n; i++) printf("%d ", a[i]); printf("\n"); } /* swap function */ void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } /* quick sort * a: array * start: the start index of array * end: the out index of array(except end) */ void quick_sort(int a[], int start, int end) { int i = 0; // for circle int pivot = start; int nFind = 0; if (start >= end) return; for(i = start+1; i < end; i++) { if (a[i] < a[pivot]) { //swap(a+i, a+pivot); //swap(&a[i], &a[pivot]); nFind = 1; pivot++; } if (nFind == 1 && i != pivot) swap(&a[i], &a[pivot]); nFind = 0; } if (pivot != start) swap(&a[pivot], &a[start]); print(a, end); // recursive quick_sort(a, start, pivot); quick_sort(a, pivot+1, end); } int partition(int a[], int start, int end) { int pivot = a[start]; while( start < end){ while(a[end] >= pivot && start < end) end--; a[start] = a[end]; while(a[start] <= pivot && start < end) start++; a[end] = a[start]; } a[start] = pivot; return start; } void quick_sort2(int a[], int start, int end) { if (start < end) { int pivot = partition(a, start, end); quick_sort2(a, start, pivot-1); quick_sort2(a, pivot+1, end); } } /* main */ int main() { int a[] = {5, 4, 7, 3, 2, 9, 1, 8}; int len = sizeof(a)/sizeof(a[0]); printf("sort befaore: \n"); print(a, len); quick_sort2(a, 0, len-1); printf("sort after: \n"); print(a, len); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<stdint.h> #include<stdbool.h> #include "db.h" #include "fgmcl.h" #define CHUNKSIZE 1024 struct cgmRes{ int read[3]; // 16 bases in each int uint32_t* matches; // pointer to list of match locations int length; // length of match list }; int mergeLists(uint32_t* a, uint32_t* b, uint32_t* c, int aLength, int bLength, int cLength, uint32_t** result) { int i = 0, j = 0, k = 0, count = 0; uint32_t* mem = NULL; /* result should be combined length of all lists */ int max = aLength+bLength+cLength; mem = (uint32_t*) malloc(sizeof(uint32_t)*max); if(mem == NULL){ printf("Unable to allocate memory!\n"); exit(-1); } /* add items in increasing order */ while(count < max) { if(i < aLength && (j >= bLength || a[i] <= b[j]) && (k >= cLength || a[i] <= c[k])){ mem[count] = a[i]; i++; } else if(j < bLength && (k >= cLength || b[j] <= c[k])){ mem[count] = b[j]; j++; } else{ mem[count] = c[k]; k++; } count++; } /* return the size of the results list */ *result = mem; return count; } int doubleMatch(uint32_t* a, uint32_t* b, int aLength, int bLength, uint32_t secLength, uint32_t** matches, uint32_t gap, uint32_t startOffset) { int i = 0, j= 0, mLength = 0; uint32_t* dubs = NULL; if(aLength == 0 || bLength == 0) { *matches == NULL; return 0; } /* maximum length is length of smaller list */ int mMax = aLength; if(bLength < mMax) mMax = bLength; dubs = (uint32_t*) malloc(sizeof(uint32_t)*mMax); if(dubs == NULL){ printf("Unable to allocate memory!\n"); exit(-1); } /* loop through the items in the first list looking for matching items in the second list */ while(i < aLength && j < bLength){ while(j < bLength){ if(b[j] < a[i] + secLength + gap) j++; else if(b[j] > a[i] + secLength + gap) break; else{ if(startOffset < a[i]){ dubs[mLength] = a[i]-startOffset; mLength++; } break; } } i++; } /* if results were found, return them, otherwise free the memory */ if(mLength > 0){ *matches = dubs; return mLength; } free(dubs); *matches = NULL; return 0; } int cgm_solver(uint32_t a, uint32_t b, uint32_t c, uint32_t** matches, struct db* database) { int sections, secLength, aLength, bLength, cLength; int double1, double2, double3; int triple; int count; uint32_t* dubMatches1 = NULL; uint32_t* dubMatches2 = NULL; uint32_t* dubMatches3 = NULL; uint32_t* tripMatches = NULL; uint32_t* temp; int keySize = 16; uint32_t* aList = NULL; uint32_t* bList = NULL; uint32_t* cList = NULL; aLength = db_query(database, a, &aList); bLength = db_query(database, b, &bList); cLength = db_query(database, c, &cList); double1 = doubleMatch(aList, bList, aLength, bLength, keySize, &dubMatches1, 0, 0); double2 = doubleMatch(aList, cList, aLength, cLength, keySize, &dubMatches2, keySize, 0); double3 = doubleMatch(bList, cList, bLength, cLength, keySize, &dubMatches3, 0, keySize); triple = doubleMatch(dubMatches1, dubMatches2, double1, double2, 0, &tripMatches, 0, 0); if(triple > 0){ *matches = tripMatches; count = triple; } else if(double1 + double2 + double3 > 0) { count = mergeLists(dubMatches1, dubMatches2, dubMatches3, double1, double2, double3, &temp); *matches = temp; } else { count = mergeLists(aList, bList, cList, aLength, bLength, cLength, &temp); *matches = temp; } /* free any allocated memory and return the number items in matches */ free(aList); free(bList); free(cList); free(dubMatches1); free(dubMatches2); free(dubMatches3); if(triple == 0) free(tripMatches); return count; } int cgm(uint32_t* genome, uint32_t gLength, int** reads, uint32_t numReads, int chunkSize, struct db* database) { int i; struct cgmRes* results = (struct cgmRes*) malloc(sizeof(struct cgmRes)*numReads); if(results == NULL){ printf("Unable to allocate memory!"); exit(-1); } #pragma omp parallel for schedule(dynamic, chunkSize) for(i = 0; i < numReads; i++) { results[i].read[0] = reads[i][0]; results[i].read[1] = reads[i][1]; results[i].read[2] = reads[i][2]; results[i].length = cgm_solver(reads[i][0], reads[i][1], reads[i][2], &results[i].matches, database); } int j = fgmLaunch(genome, gLength, results, i); free(results); return i; } int main(int argc, char* argv[]) { if(argc != 7){ printf("USAGE: cgm GENOMEFILE GENOMESIZE READFILE READFILESIZE DATABASEFILE THREADS\n"); exit(-1); } FILE* g = fopen(argv[1], "r"); int gSize = atoi(argv[2]); FILE* r = fopen(argv[3], "r"); int numReads = atoi(argv[4]); struct db* database = db_open(argv[5], 1); if(g == NULL || r == NULL || database == NULL){ printf("Error opening input file!\n"); exit(-1); } int threads = atoi(argv[6]); omp_set_num_threads(threads); uint32_t* genome = (uint32_t*) malloc(sizeof(uint32_t)*gSize); if(genome == NULL){ printf("Error allocating memory!\n"); exit(-1); } int** reads = (int**) malloc(sizeof(int*)*CHUNKSIZE); if(reads == NULL){ printf("Error allocating memory!\n"); exit(-1); } int i, j; for(i = 0; i < CHUNKSIZE; i++){ reads[i] = (int*) malloc(sizeof(int)*4); if(reads[i] == NULL){ printf("Error allocating memory!\n"); exit(-1); } } fread(genome, gSize, gSize, g); for(i = 0; i < numReads; i+=CHUNKSIZE){ for(j = 0; j < CHUNKSIZE && i+j < numReads; j++) fread(&(reads[j][0]), 16, 16, r); int num = CHUNKSIZE; if(i + CHUNKSIZE > numReads) num = numReads - i; cgm(genome,gSize,reads,num,16,database); } return 0; }
C
#include <math.h> #include <pthread.h> #include "threads.h" #include "calc_math.h" #include <stdio.h> typedef struct { float a; float h; float* v; int inicio; int fim; } InfoParaCalc; void* calc_trapezios_t(void* struct_info) { InfoParaCalc info = *((InfoParaCalc*) struct_info); for (int i = info.inicio; i < info.fim; ++i) { float x_i = info.a + i * info.h; info.v[i] = f2(x_i); } pthread_exit(NULL); } void calc_trapezios_via_threads(int numero_threads, int numero_trapezios, float a, float h, float* v) { int qtd_trapezios_por_thead = ceil((float) numero_trapezios/numero_threads); int qtd_trapezios_calculados = 0; int i = 0; pthread_t ids[numero_threads]; InfoParaCalc infos[numero_threads + 1]; while (qtd_trapezios_calculados < numero_trapezios) { int qtd_trapezios_vez_anterior = qtd_trapezios_calculados; qtd_trapezios_calculados += qtd_trapezios_por_thead; infos[i].a = a; infos[i].h = h; infos[i].v = v; infos[i].inicio = qtd_trapezios_vez_anterior; infos[i].fim = (qtd_trapezios_calculados > numero_trapezios) ? qtd_trapezios_calculados - (qtd_trapezios_calculados - numero_trapezios) : qtd_trapezios_calculados; pthread_create(&ids[i], NULL, calc_trapezios_t, (void*)&infos[i]); ++i; } for (int j = 0; j < numero_threads; ++j) { pthread_join(ids[j], NULL); } }
C
#include <stdio.h> #define SIZE 10 void stuGrade(const double* pArr, int num, double* pSum, double* pAve, double* pMax); int main() { double score[SIZE]; double sum=0, avg, max; printf(" %d л ԷϽÿ\n\n", SIZE); for (int i = 0; i < SIZE; i++) { printf("score[%d] :", i); scanf_s("%lf", &score[i]); } stuGrade(score, sizeof(score) / sizeof(*score), &sum, &avg, &max); printf("\n : %.2lf, : %.2lf, ִ : %.2lf\n", sum, avg, max); return 0; } void stuGrade(const double* pArr, int num, double* pSum, double* pAve, double* pMax) { for (int i = 0; i < num; i++) { *pSum += *(pArr + i); } *pAve = *pSum / num; *pMax = *pArr; for (int i = 1; i < num; i++) { if (*(pArr + i) > *pMax) *pMax = *(pArr + i); } }
C
/* ** add_block.c for add_block in /home/bettin_j//Documents/Malloc/src ** ** Made by jordan bettin ** Login <bettin_j@epitech.net> ** ** Started on Thu Jan 31 19:31:16 2013 jordan bettin ** Last update Fri Feb 8 09:54:54 2013 mael charles */ #include "../include/malloc.h" t_block *add_block(t_block *current, size_t size) { t_block *tmp; tmp = xsbrk(sizeof(t_block) + size); if (current != NULL) { tmp->ptr = current->ptr; tmp->size_block = current->size_block; tmp->used = 1; tmp->next = NULL; tmp->prev = tmp; } return tmp; }
C
#include <stdlib.h> #include <assert.h> #include "core/log.h" #include "core/hashtable.h" #include "symbol.h" static const int INIT_SIZE = 128; static const int STACK_CAPACITY = 128; symbol_t *new_symbol(str_t name, symbol_type_t type, void *object) { symbol_t* ret = (symbol_t*)malloc(sizeof(symbol_t)); ret->name = name; ret->type = type; ret->object = object; ret->refs = 0; return ret; } symbtable_t *new_symbtable() { symbtable_t* ret = (symbtable_t*)malloc(sizeof(symbtable_t)); assert(ret != NULL); ret->stack = new_stack(STACK_CAPACITY); assert(ret->stack != NULL); hashtable_t *global_frame = new_hashtable(INIT_SIZE); assert(global_frame != NULL); stack_push(ret->stack, (void*)global_frame); return ret; } void push_frame(symbtable_t *table) { hashtable_t *new_frame = new_hashtable(INIT_SIZE); stack_push(table->stack, (void*)new_frame); } void pop_frame(symbtable_t *table) { stack_pop(table->stack); } void put_symbol(symbtable_t *table, symbol_t *symbol) { log("Storing symbol %s", symbol->name.data); hashtable_t *frame = (hashtable_t*)stack_peek(table->stack); ht_set(frame, symbol->name, symbol); } symbol_t *get_symbol(symbtable_t *table, str_t name) { assert(name.data != NULL); execlog("Looking up symbol %s", name.data); stck_t *stack = table->stack; int index = stack->size - 1; while(index >= 0) { hashtable_t *frame = (hashtable_t*)stack->entries[index]; symbol_t *symb = (symbol_t*)ht_get(frame, name); if (symb != NULL) { return symb; } --index; } return NULL; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ struct object_id {int dummy; } ; struct llist_item {struct llist_item* next; struct object_id const* oid; } ; struct llist {scalar_t__ size; struct llist_item* front; struct llist_item* back; } ; /* Variables and functions */ struct llist_item* llist_item_get () ; __attribute__((used)) static inline struct llist_item *llist_insert(struct llist *list, struct llist_item *after, const struct object_id *oid) { struct llist_item *new_item = llist_item_get(); new_item->oid = oid; new_item->next = NULL; if (after != NULL) { new_item->next = after->next; after->next = new_item; if (after == list->back) list->back = new_item; } else {/* insert in front */ if (list->size == 0) list->back = new_item; else new_item->next = list->front; list->front = new_item; } list->size++; return new_item; }
C
#include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include "minesweeper.h" s_minesweeper_game *minesweeper_create(int width, int height, int mine_count, void (*function_update_gamestate_callback)(struct s_minesweeper_game *), void (*function_update_cell_callback)(struct s_minesweeper_game *, struct s_minesweeper_cell *, int, int)) { // Prepares the random number generator srand(time(NULL) + getpid()); // Instantiates variables. If malloc() fail: free all allocated memory! s_minesweeper_game *const game = malloc(sizeof(s_minesweeper_game)); if (game == NULL) { return (NULL); } memset(game, 0, sizeof(s_minesweeper_game)); const int array_size = width * height; game->cells = malloc(array_size * sizeof(s_minesweeper_cell)); if (game->cells == NULL) { free(game); return (NULL); } memset(game->cells, 0, array_size * sizeof(s_minesweeper_cell)); for (int idx = 0; idx < array_size; ++idx) { game->cells[idx] = malloc(sizeof(s_minesweeper_cell)); memset(game->cells[idx], 0, sizeof(s_minesweeper_cell)); if (game->cells[idx] == NULL) { while (idx >= 0) { free(game->cells[idx]); idx -= 1; } free(game->cells); free(game); return (NULL); } } // Prepares game game->state = GAME_STATE_PENDING; game->width = width; game->height = height; game->function_update_gamestate_callback = function_update_gamestate_callback; game->function_update_cell_callback = function_update_cell_callback; // Randomly place mines and increment the mine counter while (game->mine_count < mine_count) { const int pos_width = rand() % game->width; const int pos_height = rand() % game->height; s_minesweeper_cell *const cell = minesweeper_get_cell(game, pos_width, pos_height); // Set as mine if possible if (cell->has_mine == 0) { cell->has_mine = 1; game->mine_count += 1; // Update mine count on all adjacent cells s_minesweeper_cell **const adjacent_cells = minesweeper_get_adjacent_cells(game, pos_width, pos_height); for (int idx = 0; idx < ADJACENT_CELLS_MAX_COUNT; ++idx) { if (adjacent_cells[idx] != NULL) { adjacent_cells[idx]->proximity_mine_count += 1; } } free(adjacent_cells); } } return (game); }
C
/* lsattr.c Written by Corinna Vinschen <vinschen@redhat.com> This file is part of Cygwin. This software is a copyrighted work licensed under the terms of the Cygwin license. Please consult the file "CYGWIN_LICENSE" for details. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <getopt.h> #include <dirent.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <cygwin/fs.h> #include <cygwin/version.h> int Ropt, aopt, dopt, lopt, nopt; struct option longopts[] = { { "recursive", no_argument, NULL, 'R' }, { "version", no_argument, NULL, 'V' }, { "all", no_argument, NULL, 'a' }, { "directory", no_argument, NULL, 'd' }, { "help", no_argument, NULL, 'h' }, { "long", no_argument, NULL, 'l' }, { "no-headers", no_argument, NULL, 'n' }, { NULL, no_argument, NULL, 0} }; const char *opts = "+RVadhln"; struct { uint64_t flagval; char chr; const char *str; } supp_flag[] = { { FS_READONLY_FL, 'r', "Readonly" }, { FS_HIDDEN_FL, 'h', "Hidden" }, { FS_SYSTEM_FL, 's', "System" }, { FS_ARCHIVE_FL, 'a', "Archive" }, { FS_TEMP_FL, 't', "Temporary" }, { FS_SPARSE_FL, 'S', "Sparse" }, { FS_REPARSE_FL, 'r', "Reparse" }, { FS_COMPRESSED_FL, 'c', "Compressed" }, { FS_OFFLINE_FL, 'o', "Offline" }, { FS_NOTINDEXED_FL, 'n', "Notindexed" }, { FS_ENCRYPT_FL, 'e', "Encrypted" }, { FS_CASESENS_FL, 'C', "Casesensitive" }, { 0, '\0', NULL }, }; void print_long (const char *path, uint64_t flags) { int i; int first = 1; printf("%-28s ", path); for (i = 0; supp_flag[i].flagval; ++i) if (flags & supp_flag[i].flagval) { if (!first) fputs (", ", stdout); first = 0; fputs (supp_flag[i].str, stdout); } if (first) fputs ("---", stdout); fputc ('\n', stdout); } void print_short (const char *path, uint64_t flags) { int i; for (i = 0; supp_flag[i].flagval; ++i) fputc ((flags & supp_flag[i].flagval) ? supp_flag[i].chr : '-', stdout); printf(" %s\n", path); } int lsattr (const char *path) { int fd; uint64_t flags; fd = open (path, O_RDONLY); if (fd < 0) { fprintf (stderr, "%s: %s while trying to open %s\n", program_invocation_short_name, strerror (errno), path); return 1; } if (ioctl (fd, FS_IOC_GETFLAGS, &flags)) { close (fd); fprintf (stderr, "%s: %s while trying to fetch flags from %s\n", program_invocation_short_name, strerror (errno), path); return 1; } close (fd); if (lopt) print_long (path, flags); else print_short (path, flags); return 0; } int lsattr_dir (const char *path) { DIR *dir; struct dirent *de; char *subpath = (char *) malloc (strlen (path) + 1 + NAME_MAX + 1); char *comp; dir = opendir (path); if (!dir) { free (subpath); return 1; } comp = stpcpy (subpath, path); if (comp[-1] != '/') *comp++ = '/'; while ((de = readdir (dir))) { struct stat st; stpcpy (comp, de->d_name); if (lstat (subpath, &st) != 0) fprintf (stderr, "%s: %s while trying to stat %s\n", program_invocation_short_name, strerror (errno), subpath); else if (de->d_name[0] != '.' || aopt) { if (S_ISREG (st.st_mode) || S_ISDIR (st.st_mode)) lsattr (subpath); if (S_ISDIR (st.st_mode) && Ropt && strcmp (de->d_name, ".") != 0 && strcmp (de->d_name, "..") != 0) { if (!nopt) printf ("\n%s:\n", path); lsattr_dir (subpath); if (!nopt) fputc ('\n', stdout); } } } free (subpath); return 0; } static void print_version () { printf ("%s (cygwin) %d.%d.%d\n" "Get POSIX ACL information\n" "Copyright (C) 2018 - %s Cygwin Authors\n" "This is free software; see the source for copying conditions. " "There is NO\n" "warranty; not even for MERCHANTABILITY or FITNESS FOR A " "PARTICULAR PURPOSE.\n", program_invocation_short_name, CYGWIN_VERSION_DLL_MAJOR / 1000, CYGWIN_VERSION_DLL_MAJOR % 1000, CYGWIN_VERSION_DLL_MINOR, strrchr (__DATE__, ' ') + 1); } static void usage (FILE *stream) { fprintf (stream, "Usage: %s [-RVadhln] [file]...\n", program_invocation_short_name); if (stream == stderr) fprintf (stream, "Try '%s --help' for more information\n", program_invocation_short_name); if (stream == stdout) fprintf (stream, "\n" "List file attributes\n" "\n" " -R, --recursive recursively list attributes of directories and their \n" " contents\n" " -V, --version display the program version\n" " -a, --all list all files in directories, including files that\n" " start with '.'\n" " -d, --directory list directories like other files, rather than listing\n" " their contents.\n" " -l, --long print options using long names instead of single\n" " character abbreviations\n" " -n, --no-headers don't print directory headers when recursing\n" " -h, --help this help text\n" "\n" "Supported attributes:\n" "\n" " 'r', 'Readonly': file is read-only, directory is system-marked\n" " 'h', 'Hidden': file or directory is hidden\n" " 's', 'System': file or directory that the operating system uses\n" " 'a', 'Archive': file or directory has the archive marker set\n" " 't', 'Temporary': file is being used for temporary storage\n" " 'S', 'Sparse': file is sparse\n" " 'r', 'Reparse': file or directory that has a reparse point\n" " 'c', 'Compressed': file or directory is compressed\n" " 'o', 'Offline': the data of a file is moved to offline storage\n" " 'n', 'Notindexed': file or directory is not to be indexed by the\n" " content indexing service\n" " 'e', 'Encrypted': file is encrypted\n" " 'C', 'Casesensitive': directory is handled case sensitive\n" " (Windows 10 1803 or later, local NTFS only,\n" " WSL must be installed)\n"); } int main (int argc, char **argv) { int c, ret = 0; opterr = 0; while ((c = getopt_long (argc, argv, opts, longopts, NULL)) != EOF) { switch (c) { case 'R': Ropt = 1; break; case 'V': print_version (); return 0; case 'a': aopt = 1; break; case 'd': dopt = 1; break; case 'l': lopt = 1; break; case 'n': nopt = 1; break; case 'h': default: usage (c == 'h' ? stdout : stderr); return 1; } } if (optind > argc - 1) lsattr_dir ("."); else for (; optind < argc; ++optind) { struct stat st; if (lstat (argv[optind], &st) != 0) { fprintf (stderr, "%s: %s while trying to stat %s\n", program_invocation_short_name, strerror (errno), argv[optind]); ret = 1; } else if (!S_ISREG (st.st_mode) && !S_ISDIR (st.st_mode)) { fprintf (stderr, "%s: %s on %s\n", program_invocation_short_name, strerror (ENOTSUP), argv[optind]); ret = 1; } else if (S_ISDIR (st.st_mode) && !dopt) { if (lsattr_dir (argv[optind])) ret = 1; } else if (lsattr (argv[optind])) ret = 1; } return ret; }
C
#include <stdio.h> int istSchaltJahr(int jahr); int getTageInMonat(int monat, int jahr); int main(void) { int jahr = 0; int monat = 0; int tag = 0; printf("Bitte Datum eingeben: \n"); scanf("%i.%i.%i", &tag, &monat, &jahr); int tagImJahr = 0; tagImJahr += tag; for (int i = 1; i < monat; i++) tagImJahr += getTageInMonat(i, jahr); printf("\nTage vergangen: %i", tagImJahr); system("pause"); return 0; } int istSchaltJahr(int jahr) { if ((jahr % 4 == 0) && (jahr % 100 != 0) || (jahr % 400 == 0)) return 1; return 0; } int getTageInMonat(int monat, int jahr) { if (monat == 2) if (istSchaltJahr(jahr)) return 29; else return 28; else if (monat % 2 == 0) return 31; else return 30; }
C
#include <stdio.h> #include <stdlib.h> #define SIZE 10 int getline(char *s, int lim) { int c; char *t = s; while(lim-- > 0 && (c = getchar()) != EOF && c != '\n') { *t++ = c; } *t = '\0'; while(c != EOF && c != '\n') { c = getchar(); } return (t-s); } int main() { char* s = (char*)malloc(SIZE * sizeof(char)); int length = getline(s,SIZE); printf("%s \n size: %d\n", s, (length*sizeof(char))); free(s); return 0; }
C
#include <stdio.h> #define rows 2 #define columns 3 void read(int (*)[columns]); void print(int (*)[columns]); void add(int (*)[columns],int (*)[columns],int (*)[columns]); int main(){ int m1[rows][columns]; int m2[rows][columns]; int m3[rows][columns]; read(m1); read(m2); add(m1,m2,m3); printf("Answer :\n"); print(m3); return 0; } void add(int (*m1)[columns],int (*m2)[columns],int (*m3)[columns]){ for(int i=0;i<rows;i++) for(int j=0;j<columns;j++) m3[i][j]=m1[i][j]+m2[i][j]; } void read(int (*m)[columns]){ printf("Enter %d X %d matrix \n",rows,columns); for(int i=0; i<rows; ++i) for(int j=0; j<columns; ++j) scanf("%d", &m[i][j]); } void print(int (*m)[columns]){ for(int i=0;i<rows;++i){ for(int j=0;j<columns;++j){ printf("%d ",m[i][j]); } printf("\n"); } }
C
#include <errno.h> #include "../apue.h" static void sig_hup(int signo) { printf("SIGHUP received,pid = %ld\n",(long)getpid()); } static void pr_ids(char *name) { printf("%s:pid = %ld,ppid=%ld,pgrp=%ld,tpgrp = %ld\n", name,(long)getpid(),(long)getppid(),(long)getpgrp(), (long)tcgetpgrp(STDIN_FILENO)); fflush(stdout); } int main(void) { char c; pid_t pid; pr_ids("parent"); if((pid= fork())<0){ err_sys("fork error"); }else if(pid>0){ sleep(5); }else{ pr_ids("child"); signal(SIGHUP,sig_hup); kill(getpid(),SIGTSTP); pr_ids("child"); if(read(STDIN_FILENO,&c,1)!=1) printf("read error %d on controlling TTY\n",errno); } exit(0); }
C
/* * Author: Alex Hiller * Year: 2019 * Program Description: Test program to see if things import * */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> int main (int argc, char *argv[]) { printf("Hello world.\n"); uint8_t blah = 9; printf("8-bit int is: %d\n", blah); return 0; }
C
/*(2) Write a program that print your name and your grade in a new line.*/ #include <stdio.h> int main(void) { char name[20] = "Ahmed Hamdy" ; float grade = 65.00 ; printf("My Name is %s and My Grade Is %f\n" , name , grade) ; while(1); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* gradient.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tdarchiv <tdarchiv@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/23 18:50:41 by tdarchiv #+# #+# */ /* Updated: 2019/02/23 21:01:39 by tdarchiv ### ########.fr */ /* */ /* ************************************************************************** */ #include "gradient.h" #include "gradient_definitions.h" #include <stdlib.h> t_gradient create_gradient(int gradient_type) { if (gradient_type == 0) return (create_blue_yellow()); else if (gradient_type == 1) return (create_random()); else return (create_red_brown()); } uint32_t get_color_from_gradient(t_gradient gradient, float percent) { t_grad_step a; t_grad_step b; float mix_factor; t_rgb color; get_color_interval(gradient, percent, &a, &b); mix_factor = (percent - a.treshold) / (b.treshold - a.treshold); color = color_mix(mix_factor, a.color, b.color); return (rgb_pack(color)); } void get_color_interval(t_gradient gradient, float percent, t_grad_step *a, t_grad_step *b) { t_grad_step *step; int i; step = gradient.step; i = 0; while (i < (gradient.step_count - 1)) { if (percent >= step[i].treshold && percent < step[i + 1].treshold) break ; i++; } *a = step[i]; *b = step[i + 1]; } void destroy_gradient(t_gradient gradient) { free(gradient.step); }
C
//currently the program only works for S = {0, 1} #include<stdio.h> #include<stdlib.h> #include<math.h> int main(int argc, char** argv){ int n, *gen, *arr_2, *bin_arr, num, num1 ,nn, i; FILE *fptr; fptr = fopen(argv[1], "r"); fscanf(fptr, "%d", &n); gen = malloc(n * sizeof(int)); // gen = generator set for(i = 0; i < n; i++){ fscanf(fptr, "%d", &gen[i]); } fscanf(fptr, "%d", &num); arr_2 = malloc((nn = (int)(1 + log2(num)))*sizeof(int)); bin_arr = malloc(nn * sizeof(int)); num1 = num; i = 0; while(num1 != 0){ arr_2[i] = num1%2; i++; num1 = num1/2; } bin_arr[0] = 1; for(i = 1; i < nn; i++){ bin_arr[i] = bin_arr[i - 1] * 2; printf("%d + %d = %d\n", bin_arr[i - 1], bin_arr[i - 1], bin_arr[i]); } for(i = 0; i < nn; i++){ if(arr_2[i] == 1){ printf("%d ", bin_arr[i]); if(i != nn - 1){ printf("+ "); } } } printf("= %d\n", num); int sum1 = 0; for(i = 0; i < nn - 1; i++){ if(arr_2[i] == 1) sum1 += 1; } printf("No. of '+' = %d\n", nn - 1 + sum1); }
C
#include<stdio.h> void main() { int a,b,i; printf("enter two no."); scanf("%d%d",&a,&b); if(a<=100000 && b<=100000 ) for(i=a+1;i<=b-1;i++) { if(i%2!=0) { printf("%d\t",i); } } }
C
#include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #define clr(ar) memset(ar, 0, sizeof(ar)) #define read() freopen("lol.txt", "r", stdin) struct Point{ int idx, x, y, d; double theta; }; int n; struct Point ar[2010]; double centre_x, centre_y; int compare(const void* a, const void* b){ struct Point P1 = *(struct Point*)a; struct Point P2 = *(struct Point*)b; if (fabs(P1.theta - P2.theta) <= 1e-9){ double d1 = ((centre_x - P1.x) * (centre_x - P1.x)) + ((centre_y - P1.y) + (centre_y - P1.y)); double d2 = ((centre_x - P2.x) * (centre_x - P2.x)) + ((centre_y - P2.y) + (centre_y - P2.y)); if (fabs(d1 - d2) <= 1e-9) return 0; else if (d1 < d2) return -1; else return +1; } else if (P1.theta < P2.theta) return +1; else return -1; } int main(){ int t, line, i, j; scanf("%d", &t); for (line = 1; line <= t; line++){ scanf("%d", &n); centre_x = 0.0, centre_y = 0.0; for (i = 0; i < n; i++){ scanf("%d %d", &ar[i].x, &ar[i].y); ar[i].idx = i; centre_x += ar[i].x; centre_y += ar[i].y; } centre_x /= (1.0 * n), centre_y /= (1.0 * n); for (i = 0; i < n; i++) ar[i].theta = atan2((double)ar[i].y - centre_y, (double)ar[i].x - centre_x); qsort(ar, n, sizeof(struct Point), compare); for (i = 0; i < n; i++){ if (i != 0) putchar(32); printf("%d", ar[i].idx); } puts(""); } return 0; }
C
#include<stdio.h> void main() { int a,b,c,low,mid,high; printf("enter three numbers"); scanf("%d %d %d",&a,&b,&c); if(a>b) { mid=a; low=b; } else { mid=b; low=a; } if(mid>c) { high=mid; if(low>c) { mid=low; low=c; } else { mid=c; } } else { high=c; } printf("Acending order:%d %d %d\n",low,mid,high); printf("Decending order:%d %d %d",high,mid,low); }
C
/*ļ򵥲*/ #include <stdio.h> #include <stdlib.h> #define OK 1 #define ERROR 0 int num = 0; typedef struct Node { int data; struct Node * next; }Node; typedef struct Node * LinkList; /*ʼͷ*/ int InitList(LinkList * L) { *L = (LinkList)malloc(sizeof(Node)); if(*L == NULL) return ERROR; (*L)->next = NULL; return OK; } /*һnڵβ巨*/ void CreatList(LinkList *L,int n) { LinkList p = NULL,q = NULL; // *L = (LinkList)malloc(sizeof(Node)); p = *L; while(n--) { q = (LinkList)malloc(sizeof(Node)); p->next = q; q->data = num++; p = q; } p->next = NULL; } /*ĵnڵһڵ*/ void InsertNode(LinkList *L,int n) { LinkList p = NULL,q = NULL; q = (LinkList)malloc(sizeof(Node)); q->data = 100; p = (*L); while(n--) { p = p->next; } q->next = p->next; p->next = q; } /*ɾnڵ*/ void DelectNode(LinkList *L ,int n) { LinkList p = NULL,q = NULL; p = *L; n--; while(n--) { p = p->next; } q = p; p = p->next; q->next = p->next; free(p); p = NULL; } /*ÿ*/ void ClearList(LinkList *L) { LinkList p = NULL,q = NULL; p = (*L)->next; while(p->next != NULL) { q = p; free(p); p = NULL; p = q->next; } (*L)->next = NULL; } /**/ void PrintList(LinkList L) { LinkList p = NULL; p = L->next; while(p->next != NULL) { printf(" %d ",p->data); p = p->next; } printf(" %d ",p->data); } int main(void) { LinkList L; InitList(&L); printf("\n\n"); CreatList(&L,10); PrintList(L); printf("\n\n"); InsertNode(&L,5); PrintList(L); printf("\nɾ\n"); DelectNode(&L,6); PrintList(L); printf("\n\n"); ClearList(&L); PrintList(L); }
C
#include <stdio.h> #include <stdlib.h> typedef struct { char ten[20]; char ma[10]; int namsinh; float dtb; int songaynghi; }SinhVien; void NhapMang(SinhVien a[] &n) { do{ printf("Cho biet so Sinh vien: "); scanf("%d", &n); } while (n <= 0); for (int i = 1; i <= n; i++) { printf("Thong tin Sinh vien thu %d la: \n", i); printf("Ten: \n"); fflush(stdin); gets(a[i].ten); printf("Ma so: \n"); fflush(stdin); gets(a[i].ma); printf("Nam sinh :\n"); scanf("%d", &a[i].namsinh); printf("Diem Trung Binh: \n"); scanf("%f", &a[i].dtb); printf("So ngay nghi: \n"); scanf("%d", &a[i].songaynghi); } } int main() {
C
/*树的双亲表示法 节点结构定义*/ #define MAX_TREE_SIZE 100 typedef int TElemType; typedef struct PTNode // 节点结构 { TElemType data; int parent; } PTNode; typedef struct //树结构 { PTNode nodes{MAX_TREE_SIZE}; //结点数组 int r,n; //根位置和结点数 }PTree;
C
typedef struct { float x, y, z; } vec3; static vec3 vec3_add(vec3 a, vec3 b) { vec3 result; result.x = a.x + b.x; result.y = a.y + b.y; result.z = a.z + b.z; return result; } static vec3 vec3_scale(float t, vec3 a) { vec3 result; result.x = t * a.x; result.y = t * a.y; result.z = t * a.z; return result; }
C
#include <stdlib.h> /// Renaming our structures Queue and Node typedef struct node Node; typedef struct queue Queue; /// Function that creates a Queue and returns a pointer to this structure Queue* create_queue(); /// Function that checks if the Queue is empty or not int is_empty(Queue* q); /// Function that inserts a new Node at the end of the list and returns a pointer to the new Queue Queue* push(Queue* q, int value); Queue* pop(Queue* q); /// Function that prints all the data at the nodes of the queue void print(Queue* q); /// Function that free's from memory all the nodes of the queue void free_queue(Queue* q);
C
#include "ttyin.h" void print(FILE *fp, int pagesize) { static int lines = 0; char buf[BUFSIZ]; while (fgets(buf, sizeof(buf), fp) != NULL) { if (++lines < pagesize) fputs(buf, stdout); else { buf[strlen(buf) - 1] = '\0'; fputs(buf, stdout); fflush(stdout); ttyin(); lines = 0; } } } FILE *efopen(char *file, char *mode) { FILE *fp; extern char *progname; if ((fp = fopen(file, mode)) != NULL) return fp; fprintf(stderr, "%s: can't open file %s mode %s\n", progname, file, mode); exit(1); } char ttyin() /* process response from /dev/tty (version 1) */ { char buf[BUFSIZ]; static FILE *tty = NULL; if (tty == NULL) tty = efopen("/dev/tty", "r"); if (fgets(buf, BUFSIZ, tty) == NULL || buf[0] == 'q') exit(0); else /* ordinary line */ return buf[0]; }
C
// Date created: 28 Apr 2013 // Last Modified: 06 Jun 2013 (17:18:43) // // Brief: Linear spline interpolation algorithm // Input: x[n],y[n], point z // Output: value s // // License:copyleft // Author:Yang Min Wang (ymwang@chem.au.dk) #include <stdio.h> #include <assert.h> #include <lib.h> double linterp(double z, double *x, double *y, int n){ //The must z value must be in the range x_0 <= z <= x_(n-1) assert(z>=x[0] && z<=x[n-1] && n>1); double s = 0; double p = 0; int i = 0; #ifdef DEBUG printf("Inside linterp\n"); #endif //Call to the binary search algorithm i = binary_search(z, x, n); p = (y[i+1]-y[i])/(x[i+1]-x[i]); s = y[i] + p*(z-x[i]); return s; }
C
#include <stdio.h> int main(){ FILE* fp = fopen("/dev/random", "r"); char str[21]; for(int i = 0; i < 20; i++){ str[i] = fgetc(fp); } str[20] = '\0'; printf("%s\n", str); fclose(fp); return 0; }
C
#include <stdio.h> /* http://mathforum.org/dr.math/faq/faq.tower.hanoi.html Move 1: move disk 3 to post C Move 2: move disk 2 to post B Move 3: move disk 3 to post B Move 4: move disk 1 to post C Move 5: move disk 3 to post A Move 6: move disk 2 to post C Move 7: move disk 3 to post C */ void toh(int n, char src, char dest, char aux){ // termination case if(n == 1){ printf("\nMove disk 1 from %c to %c", src, dest); return; } toh(n-1, src, aux, dest); printf("\nMove disk %d from %c to %c", n, src, dest); toh(n-1, aux, dest, src); } int main(){ int n = 3; printf("\nDisk: %d",n); toh(n,'A', 'C', 'B'); return 0; }
C
#include"header.h" #include<limits.h> #include<stdbool.h> ////////////////////////////////////////////////// // // // Program to find the pair of sum in O(n) time // // Complexity in unsorted array // // // ////////////////////////////////////////////////// void findSum(int *a,int size,int sum) { bool hash[1000] = {false}; int i,res; for(i = 0 ; i < size ; ++i) { res = sum - a[i]; if(hash[res] == true) { printf("%d + %d = %d\n",res,a[i],sum); } hash[a[i]] = true; } } int main() { int *arr = null; int size,i,sum; printf("Enter size of array.\n"); scanf("%d",&size); arr = (int*) malloc(sizeof(int)*size); printf("Enter array element.\n"); for(i = 0 ; i < size ; ++i) scanf("%d",&arr[i]); printf("Enter sum to find pair.\n"); scanf("%d",&sum); findSum(arr,size,sum); return exit; }
C
#include <stdio.h> #include <stdlib.h> int main(void) { int i; float salary[5],rate; printf("Input 5 salary :\n"); for (i = 0; i < 5; ++i) { scanf("%f", &salary[i]); } printf("\n"); printf("--------------------------\n"); printf(" Salary Pay_hike Rate \n"); printf("--------------------------\n"); for (i = 0; i < 5; ++i) { if (salary[i]>16500) { rate=0.07; } else if(salary[i]<14000) { rate=0.04; } else { rate=0.055; } printf("%8.2f%10.2f%6.3f\n", salary[i],rate*salary[i],rate); } printf("--------------------------\n"); system("PAUSE"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "input.h" #define T 5 int main(); int main() { int numero[T]; int maximo; int numeroBuscado; int indiceFinal; cargarValor(numero,T); mostrarValor(numero,T); maximo = buscarMaximo(numero,T); printf("El numero maximo es: %d",maximo); printf("Ingrese un valor a buscar: "); scanf("%d",&numeroBuscado); indiceFinal= buscarValor(numero,T,numeroBuscado); printf("EL indice es %d",indiceFinal); return 0; }
C
#include <stdio.h> #include <ctype.h> #define MAX_LENGTH 101 /* Name: Tsehai Boucaud Date: 11/25/2020 Purpose: to demonstrate understanding of strings by manipulating user inputted strings to output the length, compare them, check to see if it is a palindrome string, and capitalize it. */ int getLength(char s[]) //finds the length of a string by incrimenting a counter every time a new character that is not the terminating '\0' character is found { int counter = 0; for(int i = 0; s[i] != '\0'; i++) { counter++; } return counter; } int is_equal(char s1[], char s2[]) //compares two strings to see if they are the same, returns an integer of 1 or 0 to be treated as a boolean { int equal = 0; for(int i = 0; s1[i] == s2[i] && equal == 0; i++) { if(s1[i] == '\0' || s2[i] == '\0') { equal = 1; } } return equal; } void str_copy(char dest[], char source[]) //copies one string into another. { int i = 0; for(i = 0; source[i] != '\0'; i++) { dest[i] = source[i]; } dest[i] = '\0'; } void swap(char *a, char *b) //swaps two characters { char temp = *a; *a = *b; *b = temp; } void str_reverse(char s[]) //reverses an entire string by swapping half of the characters at the start with the ones at the end. { int len = getLength(s); for(int i = 0; i < len/2; i++) { swap(&s[i], &s[len-i-1]); } } int is_palindrome(char s[]) //checks to see if a string is a palindrome by using str_copy, str_reverse, and is_equal in sucession to return the boolean given in is_equal(copy, s). { char copy[MAX_LENGTH]; str_copy(copy, s); str_reverse(copy); if(is_equal(copy, s)) { return 1; } else { return 0; } } void capitalize_word(char *str)//capitalizes the first letter in a string. { for(int i = 0; str[i] != '\0'; i++) { if(i == 0 && str[i] != ' ') { str[i] = toupper(str[i]); continue; } if(str[i] == ' ') { i = i + 1; str[i] = toupper(str[i]); continue; } else { str[i] = tolower(str[i]); } } } int main(void) { //defining variables char s1[MAX_LENGTH], s2[MAX_LENGTH]; char x; //prompting and assigning user input of two strings printf("Enter a string: "); scanf("%[^\n]s", s1); while((x=getchar() != '\n') && x != EOF); //loop to discard \n from last input and not to skip the next input printf("Enter another string: "); scanf("%[^\n]s", s2); //outputting the result of getLength with s1 and s2 printf("\nThe length of your first string is %d\n", getLength(s1)); printf("The length of your second string is %d\n", getLength(s2)); //outputting the result of is_equal(s1, s2) if(is_equal(s1, s2)==1) { printf("You entered two equal strings.\n"); } else { printf("Your strings are different.\n"); } //outputting the result of is_palindrom(s1) if(is_palindrome(s1)) { printf("%s is a palindrome string\n", s1); } else { printf("%s is not a palindrome string\n", s1); } //calling and outputting the capitalize_word function with parameter s1. capitalize_word(s1); printf("Capitalized s1 is %s ", s1); return 0; }
C
#include <stdio.h> #include <stdlib.h> typedef struct{ char nome[1000]; int dia; int mes; int ano; char cpf[13]; char sexo[400]; }cadastrarCliente; int valida_cpf(); char valida_sexo(); int valida_data_nascimento_dia(); int valida_data_nascimento_mes(); int valida_data_nascimento_ano(); char valida_nome(); char L (cadastrarCliente b){ cadastrarCliente result; printf("\nNome: %s\n", b.nome); printf("\nData de Nascimento: %d/%d /%d \n", b.dia, b.mes, b.ano); printf("\nCPF: %s\n", b.cpf); printf("\nSexo: %s\n", b.sexo); } int main(void){ cadastrarCliente P(void){ cadastrarCliente result; printf("\n Nome: "); fgets(result.nome, 1000, stdin); valida_nome(); printf("\n Dia: "); scanf("%d", &result.dia); valida_data_nascimento_dia(); printf("\n Mes: "); scanf("%d", &result.mes); valida_data_nascimento_mes(); printf("\n Ano: "); scanf("%d", &result.ano); valida_data_nascimento_ano(); printf("\n Digite CPF (apenas números): "); scanf("%s", result.cpf); valida_cpf(); printf("\n Para sexo digite [Masculino], [Feminino], ou [Outros: especifique]: "); scanf("%s", result.sexo); valida_sexo(); return result; } cadastrarCliente b; b = P(); L(b); return 0; } int valida_cpf(){ cadastrarCliente result; char cpf[13]; float resto1, resto2; int soma1, soma2, contador; printf(" Confirme o cpf: "); scanf("%s", result.cpf); setbuf(stdin,NULL); result.cpf[0] -= '0'; result.cpf[1] -= '0'; result.cpf[2] -= '0'; result.cpf[3] -= '0'; result.cpf[4] -= '0'; result.cpf[5] -= '0'; result.cpf[6] -= '0'; result.cpf[7] -= '0'; result.cpf[8] -= '0'; result.cpf[9] -= '0'; result.cpf[10] -= '0'; if((result.cpf[0] == result.cpf[1]) && (result.cpf[1] == result.cpf[2]) && (result.cpf[2] == result.cpf[3]) && (result.cpf[3] == result.cpf[4]) && (result.cpf[4] == result.cpf[5]) && (result.cpf[5] == result.cpf[6]) && (result.cpf[6] == result.cpf[7]) && (result.cpf[7] == result.cpf[8]) && (result.cpf[8] == result.cpf[9]) && (result.cpf[9] == result.cpf[10])){ }else{ soma1 = ((int)result.cpf[0] * 10)+ ((int)result.cpf[1] * 9)+ ((int)result.cpf[2] * 8)+ ((int)result.cpf[3] * 7)+ ((int)result.cpf[4] * 6)+ ((int)result.cpf[5] * 5)+ ((int)result.cpf[6] * 4)+ ((int)result.cpf[7] * 3)+ ((int)result.cpf[8] * 2); resto1 = (soma1 * 10) % 11; } if(resto1 == 10){ resto1 = 0; } soma2 = ((int)result.cpf[0] * 11) + ((int)result.cpf[1] * 10) + ((int)result.cpf[2] * 9) + ((int)result.cpf[3] * 8) + ((int)result.cpf[4] * 7) + ((int)result.cpf[5] * 6) + ((int)result.cpf[6] * 5) + ((int)result.cpf[7] * 4) + ((int)result.cpf[8] * 3) + ((int)result.cpf[9] * 2); resto2 = (soma2 * 10) % 11; if(resto2 == 10){ resto2 = 0; } if((resto1 == result.cpf[9]) && (resto2 == result.cpf[10])){ }else{ printf("\n ATENCAO \n CPF invalido, refaca a operacao. \n\n"); return main(); } } int valida_data_nascimento_dia(){ int escolha_opcao, dia; printf(" Confirme o dia: "); scanf("%d", &dia); if((dia > 0) && (dia < 32)){ }else{ printf("\n\nDados incorretos, refaça a operação.\n\n"); printf("\n 0 - Refazer a operação \n 1 - Sair\n "); scanf("%d", &escolha_opcao); }while(escolha_opcao == 0){ return main(); }while(escolha_opcao == 1){ return 0; } } int valida_data_nascimento_mes(){ int escolha_opcao, mes; printf(" Confirme o mês: "); scanf("%d", &mes); if((mes > 0) && (mes < 13)){ }else{ printf("\n\nDados incorretos, refaça a operação.\n\n"); printf("\n 0 - Refazer a operação \n 1 - Sair\n "); scanf("%d", &escolha_opcao); }while(escolha_opcao == 0){ return main(); }while(escolha_opcao == 1){ return 0; } } int valida_data_nascimento_ano(){ int escolha_opcao, ano; printf(" Confirme o ano: "); scanf("%d", &ano); if((ano > 1900) && (ano < 2019)){ }else{ printf("\n\nDados incorretos, refaça a operação.\n\n"); printf("\n 0 - Refazer a operação \n 1 - Sair\n "); scanf("%d", &escolha_opcao); }while(escolha_opcao == 0){ return main(); }while(escolha_opcao == 1){ return 0; } } char valida_sexo(){ char sexo[400]; while(sexo != 0){ printf(" Confirme o sexo: "); scanf("%s", sexo); setbuf(stdin,NULL); if((sexo[0] == 'M') || (sexo[0] == 'm')){ break; } if((sexo[0] == 'F') || (sexo[0] == 'f')){ break; } if((sexo[0] == 'O') || (sexo[0] == 'o')){ printf("\n Especifique o sexo: \n "); scanf("%s", sexo); break; }else{ printf("\nDados incorretos, refaça a operação.\n"); return main(); } } } char valida_nome(){ int contador; char nome[1000]; printf(" Confirme o nome: "); fgets(nome, 1000, stdin); if((nome[contador] >= 'a' && nome[contador] <= 'z') || (nome[contador] >= 'A' && nome[contador] <= 'Z')){ }else{ printf("\n Erro! Digito inválido, digite apenas letras.\n\n\n"); return main(); } }
C
#include "common.h" /* multithread libraries */ #include <omp.h> #ifndef K #define K 4 #endif int main(int argc, char* argv[]) { /* Validate input */ if (argc != 2) { usage(); error("Incorrect arguments!"); } uint64_t *arr, avg = 0; int64_t elapsed_time; struct timespec start, end; clock_gettime(CLOCK_REALTIME, &start); /* Assume we get a valid integer * (no overflow or conversion errors): * - creates array of size N * 2^{20} of 64 bits */ int32_t N = atoi(argv[1]), size = N * (1 << 20); arr = malloc(size * sizeof(int64_t)); /* allocate random numbers */ #pragma omp parallel num_threads(K) { /* random seed */ int32_t seed = time(NULL) ^ omp_get_thread_num(); #pragma omp for schedule(static) reduction(+:avg) for (int32_t i = 0; i < size; ++i) { arr[i] = rand_r(&seed) % LIMIT; avg += arr[i]; } } clock_gettime(CLOCK_REALTIME, &end); elapsed_time = MILLISEC(end) - MILLISEC(start); double res = (double)avg/size; fprintf(stdout, "Average output: %lf\n\ Elapsed time for MULTITHREAD application with K=%d: %ldms\n", res, K, elapsed_time); free(arr); return 0; }
C
/*1.You will be given a file with two lines. First line will contain two integers separated by commas(say X,Y). In the next line there will be Y number of integers again separated by commas. You should be able to output all the possible combinations from the Y integers (an integer can be used infinite number of times) which addition will give the value X. Example Input 10,4 2,5,3,6 The output will be: 2+2+2+2+2 2+2+3+3 2+2+6 2+3+5 5+5 The order of the output does not matter */ #include<stdio.h> #include<conio.h> #include<string.h> #include<malloc.h> typedef struct node { int data; int sum; char str[20]; struct node *next; struct node *child; } node; node * new_node(int,int,char[]); node * add_sibling(node *, int,int,char[]); node * add_child(node *, int,int,char[]); void trav(node *,int[10],int); void traverse(node *,int); void main() { int i,x,y,z,a[10]; FILE *fp; char file[256],num[10],ch; node *root = new_node(0,0,""); puts("Input file name: "); gets(file); fp=fopen(file,"r"); do { ch=getc(fp); if(isdigit(ch)) break; } while(ch!=EOF); i=0; while(isdigit(ch)) { num[i++]=ch; ch=getc(fp); } num[i]='\0'; x=atoi(num); do { ch=getc(fp); if(isdigit(ch)) break; } while(ch!=EOF); i=0; while(isdigit(ch)) { num[i++]=ch; ch=getc(fp); } num[i]='\0'; y=atoi(num); for(z=0; z<y; z++) { do { ch=getc(fp); if(isdigit(ch)) break; } while(ch!=EOF); i=0; while(isdigit(ch)) { num[i++]=ch; ch=getc(fp); } num[i]='\0'; a[z]=atoi(num); } for(i=0; i<y; i++) trav(root,a,y); printf("\nOUTPUT:"); traverse(root,x); fclose(fp); getch(); } void trav(node *root,int a[10],int y) { int i; if(root==NULL) return; trav(root->next,a,y); if(root->child==NULL) { for(i=0; i<y; i++) add_child(root,a[i],root->sum,root->str); return; } trav(root->child,a,y); } void traverse(node *root,int x) { if(root==NULL) return; traverse(root->next,x); if(root->sum==x) printf("\n%.*s",strlen(root->str)-1,root->str); traverse(root->child,x); } node * new_node(int data,int s,char st[10]) { node *new_node = malloc(sizeof(node)); if ( new_node ) { new_node->next=NULL; new_node->child = NULL; new_node->data = data; new_node->sum = data+s; strcpy(new_node->str,""); if(new_node->data!=0) { itoa(new_node->data,new_node->str,20); strcat(new_node->str,"+"); strcat(new_node->str,st); } } return new_node; } node * add_sibling(node * n, int data,int s,char st[20]) { if ( n == NULL ) return NULL; while (n->next) n = n->next; return (n->next = new_node(data,s,st)); } node * add_child(node * n, int data,int s,char st[20]) { if ( n == NULL ) return NULL; if ( n->child ) return add_sibling(n->child, data,s,st); else return (n->child = new_node(data,s,st)); }
C
#include <stdio.h> #include <ctype.h> #include "api.h" #include "array_operations.h" //Programed implemented for base 10 at the moment APInt * str2api (char *i) { int index = 0; char sign = '+'; // finds the sign if one exists if (i[0] == '+') { index++; } else if (i[0] == '-') { index++; sign = '-'; } for (; '\0' != i[index] && isdigit (i[index]); index++); // if the given string is an integer. if ('\0' == i[index]) { index--; APInt *api = (APInt *) malloc (sizeof (APInt)); if (sign == '+') { api->sign = positive; } else if (sign == '-') { api->sign = negative; } api->list = array_list_init (); for (; index > -1 && isdigit (i[index]); index--) { add_last (api->list, i[index] - '0'); } return api; } // if the given string is illegal else { printf ("Illegal characters exist in the given string\n"); return NULL; } } char * api2str (APInt * i) { if (i->list->size == 0) { char *ret = (char *) malloc (sizeof (char) * 2); ret[0] = '0'; ret[1] = '\0'; return ret; } char *ret = (char *) malloc (sizeof (char) * ((i->list->size) + 2)); int j = 0; if (i->sign == positive) { ret[0] = '+'; } else { ret[0] = '-'; } for (int k = i->list->size; k > 0; k--) { ret[k] = i->list->array[j++] + '0'; } ret[++j] = '\0'; return ret; } /*APInt * str2api (char * i){ int index = 0; char sign = '+'; // finds the sign if one exists if (i[0] == '+'){ index++; } else if (i[0] == '-'){ index++; sign = '-'; } for (; '\0' != i[index] && isdigit(i[index]); index++); // if the given string is an integer. if ('\0' == i[index]){ index--; APInt * api = (APInt * ) malloc(sizeof(APInt)); if (sign == '+'){ api->sign = positive; } else if (sign == '-'){ api->sign = negative; } api->p_list = NULL; api->list = array_list_init(); for(; index > -1 && isdigit(i[index]) ; index--){ add_last(api->list, i[index]-'0'); } return api; } // if the given string is illegal else if ('.' != i[index] && !isdigit(i[index])){ printf("Illegal characters exist in the given string\n"); return NULL; } // if the given string has a '.' in it else if ('.' == i[index]){ int int_size = index++ - 1; for (; '\0' != i[index] && isdigit(i[index]); index++); // if the given string is a true float if ('\0' == i[index]){ APInt * api = (APInt * ) malloc(sizeof(APInt)); if (sign == '+'){ api->sign = positive; } else if (sign == '-'){ api->sign = negative; } api->p_list = array_list_init(); int p_size = int_size + 2; add_last(api->p_list, 0); for (; i[p_size] != '\0';p_size++){ add_last(api->p_list, i[p_size]-'0'); } api->list = array_list_init(); for(; int_size > -1 && isdigit(i[int_size]) ; int_size--){ add_last(api->list, i[int_size]-'0'); } return api; } // if the given array is illegal else { printf("Illegal characters exist in the given string\n"); return NULL; } } return NULL; } */
C
/* :: page.h author Robert Woods <hi@robertwoods.me> course Operating Systems assign Assignment 2: Virtual Memory Management A simple struct representing a single page in virtual memory. PageNumber is calculated before the page is created, as a function of some specified page size. The struct includes fields representing reference and modified bits treated separately, and an 8-bit unsigned integer representing a flag sequence for recording more granular information about how recently a page was referenced. */ #ifndef __PAGE_H__ #include "./memsim.h" typedef struct { uint PageNumber; bool Referenced, Modified; uint8 ReferenceBits; } page; page *NewPage(uint); #define __PAGE_H__ #endif
C
#include <stdlib.h> #include <stdio.h> #include <sequence.h> #include <string.h> Sequence* newSequence(unsigned char firstByte, unsigned long long hashSize) { Sequence* newSequence = malloc(sizeof(Sequence)); newSequence->length = 1; newSequence->usage = 0; newSequence->code = 0; newSequence->hash = firstByte * 27; newSequence->bucket = (newSequence->hash % hashSize); newSequence->next = NULL; newSequence->data.bytes[0] = firstByte; // allocating every entry in bytes for // newSequence->data.bytes[1] = 0; // newSequence->data.bytes[2] = 0; // no // newSequence->data.bytes[3] = 0; // newSequence->data.bytes[4] = 0; // loss // newSequence->data.bytes[5] = 0; // newSequence->data.bytes[6] = 0; // of data // newSequence->data.bytes[7] = 0; return newSequence; } void deleteSequence(Sequence* sequence) { free(sequence); } Sequence* copySequenceAppending(Sequence* sequence, unsigned char newByte, unsigned long long hashSize) { Sequence* tempSequence = newSequence(sequence->data.bytes[0], hashSize); //tempSequence->hash = newByte; unsigned long long newHash = newByte; tempSequence->length = sequence->length + 1; int i = 0; while(sequence->data.bytes[i] != 0){ // find a free spot in the // sequenes data.bytes for // a new byte tempSequence->data.bytes[i] = sequence->data.bytes[i]; newHash += tempSequence->data.bytes[i]; //tempSequence->hash += tempSequence->data.bytes[i]; i++; } tempSequence->data.bytes[i] = newByte; // add the new byte tempSequence->hash *= newHash * 27; // update the hash tempSequence->bucket = tempSequence->hash % hashSize; // and the bucket return tempSequence; } unsigned int outputSequence(Sequence* sequence, void (*writeFunc)(unsigned char c, void* context), void* context) { int i = 0; while(sequence->data.bytes[i] != 0){ // for chars in data.bytes writeFunc(sequence->data.bytes[i], context); // print chars in data.bytes i++; } return i; } bool identicalSequences(Sequence* a, Sequence* b) { if(a->length != b->length) return false; // make sure length is same int i = 0; while(a->data.bytes[i] != 0 && b->data.bytes[i] != 0) { // check each char if (a->data.bytes[i] != b->data.bytes[i]) return false; i++; } return true; }
C
/* ALUNO: LUCAS DA SILVA MOUTINHO - 15/0015747 PROFESSOR: ALCHIERI ESTUDO DIRIGIDO 8 - PROGRAMAÇÃO CONCORRENTE - 2/2018 PROBLEMA DOS FILOSOFOS - FILOSOFOS SO EXISTEM PRA PENSAR E COMER. EM UMA MESA COM 5 FILOSOS, ENTRE CADA UM HA UMA COLHER PARA COMER O FILOSOFO PRECISA DE USAR UM GARFO NA ESQUERDA E UM NA DIREITA. QUANDO O FILOSOFO PARA DE PENSAR E QUER COMER ELE PEGA OS DOIS GARFOS E COME, O FILOSOFO ADJACENTE NAO PODE COMER POIS O GARFO ESTA SENDO USADO. SOLUÇÃO 1 - MENOS OTIMIZADA: #DEFINE N = 5 #DEFINE ESQ(I) (I + N - 1)%N #DEFINE DIR(I) (I+1)%N SEMAFORO S[N] = {1,...,1} LOCK L; filosofos(int i){ while(true){ // pensam . . . lock(l); sem_wait(s[esq(i)]); sem_wait(s[dir(i)]); unlock(l); // comem sem_post(s[esq(i)]); sem_post(s[dir(i)]); } } SOLUÇÃO 2 - MAIS OTIMIZADA: #DEFINE N = 5 #DEFINE ESQ(I) (I + N - 1)%N #DEFINE DIR(I) (I+1)%N #DEFINE COMENDO 0 #DEFINE FAMINTO 1 #DEFINE PENSANDO 2 int est[N] = {PENSANDO,...,PENSANDO}; LOCK L; SEMAFORO S[N] = {0,...,0} teste(int i){ if(est[i] == FAMINTO && est[esq(i)] != COMENDO && est[dir(i)] != COMENDO){ est[i] = COMENDO; sem_post(s[i]) } } pega_garfos(int i){ lock(l) est[i] = FAMINTO teste(i); unlock(l) sem_wait(s[i]); } devolve_garfos(int i){ lock(l) est[i] = PENSANDO teste(esq(i)); teste(dir(i)); unlock(l) } filosofos(int i){ while(true){ // pensam . . . pega_garfos(i); // comem devolve_garfos(i); } } */ #include <stdlib.h> #include <stdio.h> #include <pthread.h> #include <unistd.h> #include <semaphore.h> #define TRUE 1 #define N 5 #define COMENDO 0 #define FAMINTO 1 #define PENSANDO 2 pthread_t filosofo[N]; sem_t semaforo[N]; pthread_mutex_t l = PTHREAD_MUTEX_INITIALIZER; int est[N]; int dir(int i){ return (i+1)%N; } int esq(int i){ return (i+N-1)%N; } void inicializa_estado(){ int i; for(i = 0; i < N; i++){ est[i] = PENSANDO; } } void teste(int i){ if(est[i] == FAMINTO && est[esq(i)] != COMENDO && est[dir(i)] != COMENDO){ est[i] = COMENDO; sem_post(&semaforo[i]); } } void pega_garfos(int i){ pthread_mutex_lock(&l); printf("Filosofo %d acordou e está com fome\n", i); est[i] = FAMINTO; teste(i); pthread_mutex_unlock(&l); sem_wait(&semaforo[i]); printf("Filosofo %d pegando os garfos %d e %d\n", i, i, dir(i)); } void devolve_garfos(int i){ pthread_mutex_lock(&l); printf("Filosofo %d acabou de comer...devolvendo garfos %d e %d\n", i, i, dir(i)); est[i] = PENSANDO; teste(dir(i)); teste(esq(i)); pthread_mutex_unlock(&l); } void *filosofando(void *arg){ int id = *((int *)arg); while(TRUE){ printf("Filosofo %d está pensando: Ohmmmmmm...\n", id); /*PENSANDO*/ sleep(5); pega_garfos(id); printf("Filosofo %d esta comendo: NHAM NHAM!\n", id); /*COMENDO*/ sleep(3); devolve_garfos(id); sleep(1); } pthread_exit(0); } int main(){ int i; int *id; for(i = 0; i < N; i++){ sem_init(&semaforo[i], 0, 0); } inicializa_estado(); for (i = 0; i < N; i++){ id = (int *)malloc(sizeof(int)); *id = i; pthread_create(&filosofo[i], NULL, filosofando, (void *)(id)); } pthread_join(filosofo[0], NULL); return 0; }
C
#include<stdio.h> #include<stdlib.h> #define NUMEROMAXIMO 10000000 /* Para a parte do trabalho referente a um programa IOBound utilizaremos um programa que gera numeros aleatórios e os salva em um arquivo de destino */ int main(){ int contador = 0; FILE *numerosOriginal; numerosOriginal = fopen("numeros.txt", "w"); for(int i=0;i < NUMEROMAXIMO; i++ ){ float a = rand(); fprintf(numerosOriginal, "%f\n", a); } fclose(numerosOriginal); }
C
//Nome: Lucas Mateus Fernandes //Ra: 0035411 //Data: 01/07/2019 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "AnaliseEntrada.h" #include "TratamentoString.h" #include "Palavra.h" #include "Lista.h" #include "OpenHash.h" #include "ListaHash.h" #include "ABB.h" #include "AVL.h" #include "Clock.h" //Le um arquivo txt e verifica as linhas em que as palavras aparecem TAD *leituraTexto(char *nomeArquivoTexto, TAD *tadEstrutura){ printf("\n\nPROCESSAMENTO"); //Abre Arquivo FILE *arquivo; arquivo = fopen(nomeArquivoTexto, "r"); //Verifica se foi possivel abrir o arquivo if(arquivo == NULL){ printf("Erro ao abrir o arquivo '%s' ",nomeArquivoTexto); return NULL; } //variavel de controle (linha em que a palavra aparece) int numeroLinha = 1; //Percorre Arquivo int fimArquivo = 0; do{ //le uma palavra char *newPalavra = lerPalavra(arquivo); //Tira a pontuação do final da palavra newPalavra = tiraPontuacao(newPalavra); //Se a palavra for valida muda seus indices em todas as palavras if(palavraValida(newPalavra)){ //printf("\nPalavra = %s",newPalavra); //ReCria a estrutura N vezes //Lista tadEstrutura = tadInserirLISTA(tadEstrutura, newPalavra, numeroLinha); //ABB tadEstrutura = tadInserirABB(tadEstrutura, newPalavra, numeroLinha); //AVL tadEstrutura = tadInserirAVL(tadEstrutura, newPalavra, numeroLinha); //Tabela Hash tadEstrutura = tadInserirHASH(tadEstrutura, newPalavra, numeroLinha); //Tabela Hash com Lista tadEstrutura = tadInserirHASH_LISTA(tadEstrutura, newPalavra, numeroLinha); }else{ //printf("\nPalavraInvalida = %s",newPalavra); } //Verifica qual foi o criterio de parada para a leitura da palavra int criterio = criterioParada(arquivo); if(criterio == 0){}//Espaço else if(criterio == 1){numeroLinha++;}//\n else if(criterio == -1){ fimArquivo = 1;}//EOF }while(!fimArquivo); //Fecha o Arquivo fclose(arquivo); //Retorna struct com todas as estruturas e o tempo de processamento de cada uma return tadEstrutura; } //Leitura palavras Validas ( contrução das N estruturas) TAD *leituraTreinamento(char *nomeArquivoPalavras){ printf("\n\nTREINAMENTO"); //Estruturas TAD *tadEstrutura = initEstrutura(); //Abre Arquivo FILE *arquivo; arquivo = fopen(nomeArquivoPalavras, "r"); //Verifica se foi possivel abrir o arquivo if(arquivo == NULL){ printf("Erro ao abrir o arquivo '%s' ",nomeArquivoPalavras); return NULL; } //Percorre Arquivo int fimArquivo = 0; do{ //le uma palavra char *newPalavra = lerPalavra(arquivo); //Tira a pontuação do final da palavra newPalavra = tiraPontuacao(newPalavra); //Se a palavra for valida a implementa em todas as estruturas if(palavraValida(newPalavra)){ //printf("\nnewPalavra = %s",newPalavra); //ReCria a estrutura N vezes //Lista tadEstrutura = tadInserirLISTA(tadEstrutura, newPalavra, -1); //ABB tadEstrutura = tadInserirABB(tadEstrutura, newPalavra, -1); //AVL tadEstrutura = tadInserirAVL(tadEstrutura, newPalavra, -1); //Tabela Hash tadEstrutura = tadInserirHASH(tadEstrutura, newPalavra, -1); //Tabela Hash com Lista tadEstrutura = tadInserirHASH_LISTA(tadEstrutura, newPalavra, -1); }else{ //printf("\nPalavraInvalida = %s",newPalavra); } //Verifica se chegou ao fim do arquivo if(criterioParada(arquivo)==-1){ fimArquivo = 1;} }while(!fimArquivo); //Fecha o Arquivo fclose(arquivo); //Retorna struct com todas as estruturas return tadEstrutura; } char *lerPalavra(FILE *arquivo){ //Le uma palavra até espaço pula linha ou EOF int tamanho = 0; char *palavra = malloc(sizeof(char*)); char letra; int flagContinuar; do{ //reseta flag flagContinuar = 1; //Le um caractere letra = fgetc(arquivo); //Verifica se o caractere lido é um criterio de parada if(letra == ' ' || letra == '\n' || letra == EOF){ flagContinuar = 0; palavra = realloc(palavra, (tamanho+1) * sizeof(char*)); palavra[tamanho] = '\0'; }else{ //Aumenta a quantidade de caracteres lidos tamanho++; //Ajusta o vetor para caber o novo caractere palavra = realloc(palavra, tamanho * sizeof(char*)); //Conseguiu alocar if(palavra != NULL){ //Converte para letra minuscula palavra[tamanho-1] = tolower(letra); }else{//Não conseugiu alocar printf("\nImpossivel realocar mais espaço para a palavra a ser lida -Memoria FULL-\n"); } } }while(flagContinuar); return palavra; } char *tiraPontuacao(char* string){ //Verifica o tamanho da palavra int tamanho = strlen(string); //Cria flag para controle do while int flagMudanca; do{ //Reseta flag flagMudanca = 0; // ! " # $ % & ' ( ) * + , - . / if((string[tamanho -1] >= 33) && (string[tamanho -1] <= 47)){ string[tamanho -1] = '\0'; flagMudanca++; } // : ; < = > ? @ if((string[tamanho -1] >= 58) && (string[tamanho -1] <= 64)){ string[tamanho -1] = '\0'; flagMudanca++; } // [ \ ] ^ _ ` if((string[tamanho -1] >= 91) && (string[tamanho -1] <= 96)){ string[tamanho -1] = '\0'; flagMudanca++; } // { | } ~ if((string[tamanho -1] >= 123) && (string[tamanho -1] <= 126)){ string[tamanho -1] = '\0'; flagMudanca++; } //Verifica se teve alguma alteração if(flagMudanca == 0){ break; } }while(flagMudanca); return string; } int criterioParada(FILE *arquivo){ //LEGENDA // -1 == EOF // 0 == Nada em especifico // 1 == \n //Verifica se chegou ao fim caso sim aborta a missao if(feof(arquivo)){ return (-1); } //volta o ponteiro fseek(arquivo,-1,SEEK_CUR); //Le novamente a ultima caractere char caractere = fgetc(arquivo); //Verifica qual caractere interrompeu a leitura (" Muda Indice") if(caractere == '\n'){return 1;} else{return 0;} } TAD *initEstrutura(){ //Lista de estruturas TAD *estrutura = NULL; estrutura = malloc(sizeof(TAD)); //Estruturas estrutura->ABB = NULL; estrutura->AVL = NULL; estrutura->HASH = NULL; estrutura->LISTA = NULL; estrutura->HASH_LISTA = NULL; //Calcula TempoProcessamento estrutura->timePABB = 0; estrutura->timePAVL = 0; estrutura->timePHASH = 0; estrutura->timePHASH_LISTA = 0; estrutura->timePLISTA = 0; //Calcula TempoExibição estrutura->timeEABB = 0; estrutura->timeEAVL = 0; estrutura->timeEHASH = 0; estrutura->timeEHASH_LISTA = 0; estrutura->timeELISTA = 0; return estrutura; } TAD *tadInserirABB(TAD *estrutura, char *palavra, int pagina){ //Começa a contar o tempo para processar a informação dentro da ABB float auxTimeI = start(); //Inserir Palavra ou indice na ABB NoABB *ptrABB = InserirPalavraABB(estrutura->ABB, palavra, pagina); //Para de contar o tempo gasto na ABB float auxTimeF = stop(); estrutura->timePABB += delta(auxTimeI, auxTimeF); //Cria a estrutura N vezes if(ptrABB != NULL){ estrutura->ABB = ptrABB; } return estrutura; } TAD *tadInserirAVL(TAD *estrutura, char *palavra, int pagina){ //Cria a estrutura N vezes float auxTimeI = start(); NoAVL *ptrAVL = InserirPalavraAVL(estrutura->AVL, palavra, pagina); float auxTimeF = stop(); estrutura->timePAVL += delta(auxTimeI, auxTimeF); if(ptrAVL != NULL){ estrutura->AVL = ptrAVL; } return estrutura; } TAD *tadInserirLISTA(TAD *estrutura, char *palavra, int pagina){ //Começa a contar o tempo para processar a informação dentro da LISTA float auxTimeI = start(); //Inserir Palavra ou indice na LISTA estrutura->LISTA = InserirPalavraLista(estrutura->LISTA, palavra, pagina); //Para de contar o tempo gasto na LISTA float auxTimeF = stop(); estrutura->timePLISTA += delta(auxTimeI, auxTimeF); return estrutura; } TAD *tadInserirHASH(TAD *estrutura, char *palavra, int pagina){ //Se a tanela estiver Null aloca a if(estrutura->HASH == NULL){ estrutura->HASH = IniciaOpenHash(); } //Começa a contar o tempo para processar a informação dentro da HASH float auxTimeI = start(); //Inserir Palavra ou indice na HASH InserirPalavraOpenHash(estrutura->HASH, palavra, pagina); //Para de contar o tempo gasto na HASH float auxTimeF = stop(); estrutura->timePHASH += delta(auxTimeI, auxTimeF); return estrutura; } TAD *tadInserirHASH_LISTA(TAD *estrutura, char *palavra, int pagina){ //Se a tabela estiver Null aloca a if(estrutura->HASH_LISTA == NULL){ estrutura->HASH_LISTA = IniciaListaHash(); } //Começa a contar o tempo para processar a informação dentro da HASH float auxTimeI = start(); //Inserir Palavra ou indice na HASH InserirPalavraListaHash(estrutura->HASH_LISTA, palavra, pagina); //Para de contar o tempo gasto na HASH float auxTimeF = stop(); estrutura->timePHASH_LISTA += delta(auxTimeI, auxTimeF); return estrutura; } //###################################################################################### //###################################################################################### //######################################################################################
C
#include<stdio.h> #include<pthread.h> #include<stdlib.h> void *Loop_1(void); void *Loop_2(void); int N = 0; void main() { pthread_t thread_1, thread_2; if((thread_1 = pthread_create(&thread_1, NULL, Loop_1, NULL)) == -1) { printf("Thread Create Fail.\n"); exit(1); } if((thread_2 = pthread_create(&thread_2, NULL, Loop_2, NULL)) == -1) { printf("Thread Create Fail.\n"); exit(1); } pthread_join(thread_1, NULL); pthread_join(thread_2, NULL); getchar(); } void* Loop_1(void) { for(int i = 0; i < 100; i++) { N++; _sleep(1); } } void* Loop_2(void) { for(int i = 0; i < 100; i++) { printf("N: %d\n", N); _sleep(1); } }
C
#include "ch32v10x.h" /****************************************************************************************** * Function Name : SetSysClock * Description : Sets System clock frequency to 72MHz and configure HCLK, PCLK2 and PCLK1 prescalers. * Input : None * Return : None *******************************************************************************************/ static void SetSysClock(void) { __IO uint32_t StartUpCounter = 0, HSEStatus = 0; RCC->CTLR |= ((uint32_t)RCC_HSEON); /* Wait till HSE is ready and if Time out is reached exit */ do { HSEStatus = RCC->CTLR & RCC_HSERDY; StartUpCounter++; } while((HSEStatus == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT)); if ((RCC->CTLR & RCC_HSERDY) != RESET) { HSEStatus = (uint32_t)0x01; } else { HSEStatus = (uint32_t)0x00; } if (HSEStatus == (uint32_t)0x01) { /* Enable Prefetch Buffer */ FLASH->ACTLR |= FLASH_ACTLR_PRFTBE; /* Flash 2 wait state */ FLASH->ACTLR &= (uint32_t)((uint32_t)~FLASH_ACTLR_LATENCY); FLASH->ACTLR |= (uint32_t)FLASH_ACTLR_LATENCY_2; /* HCLK = SYSCLK */ RCC->CFGR0 |= (uint32_t)RCC_HPRE_DIV1; /* PCLK2 = HCLK */ RCC->CFGR0 |= (uint32_t)RCC_PPRE2_DIV1; /* PCLK1 = HCLK */ RCC->CFGR0 |= (uint32_t)RCC_PPRE1_DIV1; RCC->CFGR0 &= (uint32_t)((uint32_t)~(RCC_PLLSRC | RCC_PLLXTPRE | RCC_PLLMULL)); /* PLL configuration: PLLCLK = HSE * ? */ RCC->CFGR0 |= (uint32_t)(RCC_PLLSRC_HSE | RCC_PLLMULL11); /* Enable PLL */ RCC->CTLR |= RCC_PLLON; /* Wait till PLL is ready */ while((RCC->CTLR & RCC_PLLRDY) == 0) { } /* Select PLL as system clock source */ RCC->CFGR0 &= (uint32_t)((uint32_t)~(RCC_SW)); RCC->CFGR0 |= (uint32_t)RCC_SW_PLL; /* Wait till PLL is used as system clock source */ while ((RCC->CFGR0 & (uint32_t)RCC_SWS) != (uint32_t)0x08) { } } else { /* * If HSE fails to start-up, the application will have wrong clock * configuration. User can add here some code to deal with this error */ } } /****************************************************************************************** * Function Name : SystemInit * Description : Setup the microcontroller system Initialize the Embedded Flash Interface, * the PLL and update the SystemCoreClock variable. * Input : None * Return : None *******************************************************************************************/ void SystemInit (void) { RCC->CTLR |= (uint32_t)0x00000001; RCC->CFGR0 &= (uint32_t)0xF8FF0000; RCC->CTLR &= (uint32_t)0xFEF6FFFF; RCC->CTLR &= (uint32_t)0xFFFBFFFF; RCC->CFGR0 &= (uint32_t)0xFF80FFFF; RCC->INTR = 0x009F0000; SetSysClock(); }
C
/* ** EPITECH PROJECT, 2018 ** my_strndup.c ** File description: ** Duplicates a given string (n bytes) */ #include <stdlib.h> #include "my.h" char *my_strndup(char const *src, int n) { int len = my_strlen(src); int size = (len > n) ? n : len; char *str = malloc(sizeof(char) * (size + 1)); if (str == NULL) return (NULL); my_strncpy(str, src, n); return (str); }
C
/*______________mystring_ptrs.c_____________ * assignement 1 * hy255 * Tsolis Dimitris * email:tsolis@csd.uoc.gr * * Contains a function implementation of the interface introduced by * mystring.h library. * This implementation is done with use of pointers * */ #include<assert.h> #include<stddef.h> /*******HELPING FUNCTIONS*********/ /*--------------Function last_index----------------- * Returns the adrress of the '\0' character. * * Arguments: * -string *a: The string that the character is in * * Returns: * -char *i: The index of NULL char * */ char *last_index(char *a){ char *i; for(i=a;*i!='\0';i++){ ; } return i; } /**************FUNCTION IMPLEMENTATION******************/ /*--------Function: ms_length--------- * Retunrs the length of the string passed sa an argument. * * Arguments: * -const char *:The string to find its length * Returns: * -size_t :The unsigned integer representing the length * * Assertions: * -Checks if the string argument is <NULL>.If true then exit * printing an error message else continue. * */ size_t ms_length(const char *cs){ const char *i; assert(cs); for(i=cs;*i!='\0';i++){ ; } return i-cs; } /*---------Function: ms_copy---------- * Copies the second string argument to the first including the '\0' * character. * * Arguments: * -char *: The destination string.Must be large enough to fit the * source string. * * -const char*: The source string that will be copied * * Return: * -char *: The pointer to start of the copied string (destination string "first arg") * * Assertions: * -Checks if the string (destination,source) are NULL. * If true exits the programm printing an error message. * * */ char *ms_copy(char *str,const char *cs){ const char *i; char *j; assert(str); assert(cs); if(*str=='\0' && *cs=='\0'){ return ""; } for(i=cs,j=str;i-cs!=ms_length(cs)+1;i++,j++){ *j=*i; } return str; } /*---------Function: ms_ncopy---------- * Copies at most n chars from the second string argument to the first including the '\0' * character.If the destination argument is bigger then the remaining chars are replaced * by '\0'. * * Arguments: * -char *: The destination string.Must be large enough to fit the * source string. * * -const char*: The source string that will be copied * * -size_t : The number of chars to be copied. * * Return: * -char *: The pointer to start of the copied string (destination string "first arg") * * Assertions: * -Checks if the string (destination,source) are NULL. * If true exits the programm printing an error message. * * */ char *ms_ncopy(char *str,const char *cs,size_t n){ const char *i; char *j; assert(str); assert(cs); if(*str=='\0' && *cs=='\0') { return ""; } for(i=cs,j=str;i-cs<n;i++,j++){ *j=*i; } *j='\0'; return str; } /*----------Function: ms_concat------------ * Concats the second argument string at the fo the first. * * Arguments: * -char *: The first arguments string at whose the end the first is concated. * * -const char* : The second argument string. * * Return: * -char *: The pointer to start of the first string argument. * * Assertions: * -Checks if the strings (first,second) are NULL. * If true exits the programm printing an error message. * */ char *ms_concat(char *str,const char *cs){ char *j; const char *i=cs; assert(str); assert(cs); if(*str=='\0' && *cs=='\0'){ return ""; } for(j=last_index(str) ; i-cs<=ms_length(cs) ; i++,j++){ *j=*i; } return str; } /*----------Function: ms_nconcat------------ * Concats the first n characters shown by the 3rd argument of the second string * argument string at the end of the first. * * Arguments: * -char *: The first arguments string at whose the end the first is concated. * * -const char* : The second argument string. * * -size_t: The number of characters to be concated. * * Return: * -char *: The pointer to start of the first string argument. * * Assertions: * -Checks if the strings (first,second) are NULL. * If true exits the programm printing an error message. * */ char *ms_nconcat(char *str,const char *cs,size_t n){ char *j; const char *i=cs; assert(cs); assert(str); if(*str=='\0' && *cs=='\0'){ return ""; } for(j=last_index(str); i-cs<n ;i++,j++){ *j=*i; } *j='\0'; return str; } /*---------Function: ms_compare---------- * Compares lexicographically the 2 strigns passed as argumets to this function. * * Arguments: * -const char* : The first of the 2 strings to be compared. * * -const char* : The second string to be compared. * Return: * -An integer inticating the result of the comparison. * Return value <0 if the first str< second str, 0 if first str==second str, * and >0 if the first str> second str. * * Assertions: * -Checks if the strings (first,second) are NULL. * If true exits the programm printing an error message. * */ int ms_compare(const char *csa,const char *csb){ const char *j; const char *i; int res=0; assert(csa); assert(csb); for(i=csa,j=csb;*i!='\0' || *j!='\0';i++,j++){ res=*i-*j; if(res<0 || res>0){ return res; } } return res; } /*-----------Function: ms_ncompare--------------- * Compares lexicographically at most n chars(n is the 3rd argument) of the first string * with the 2nd string passed as argumets to this function. * * Arguments: * -const char* : The first of the 2 strings to be compared. * * -const char* : The second string to be compared. * * -size_t : The number of chars of the first string argument. * Return: * -An integer inticating the result of the comparison. * Return value <0 if the first str< second str, 0 if first str==second str, * and >0 if the first str> second str. * * Assertions: * -Checks if the strings (first,second) are NULL. * If true exits the programm printing an error message. * */ int ms_ncompare(const char *csa,const char *csb,size_t n){ const char *i; const char *j; int res=0; assert(csa); assert(csb); for(i=csa,j=csb;(*i!='\0' || *j!='\0') && (i-csa<n && j-csb<n);i++,j++){ res=*i-*j; if(res<0 || res>0){ return res; } } return res; } /*-------------Function: ms_search-------------- * Searches and finds the first apereance of the second string argument in the first. * * Arguments: * -const char *: The string to look in. * * -const char *: The pattern to find in the first. * * Returns: * -A pointer to the first appearance of the pattern in the first * NULL if the pattern does not exist. * * * Assertions: * -Checks if the 2 string arguments are NULL. * If true exits the function printing an error message. * */ char *ms_search(const char *csa,const char *pat){ const char *i; assert(csa); assert(pat); for(i=csa;*i!='\0';i++){ if(ms_ncompare(i,pat,ms_length(pat))==0){ return (char *)i; } } return NULL; }
C
/** Autor: Gabriel Dias **/ /** * Faa um algoritmo que receba um cdigo correspondente ao cargo de um funcionrio e * imprima seu cargo e o percentual de aumento ao qual este funcionrio tem direito * segundo a tabela a seguir: * * Cdigo Cargo Percentual * 1 Escriturrio 50 * 2 Secretrio 35 * 3 Caixa 20 * 4 Gerente 10 * 5 Diretor 0 * **/ // Bibliotecas padro #include <stdio.h> #include <locale.h> int main (){ // Configura o idioma de acordo com a localizao setlocale(LC_ALL, "portuguese"); // Variveis int codigo; // Processamento printf("Digite o cdigo do cargo: "); scanf("%d", &codigo); switch (codigo){ case 1: printf("\n O cargo correpondente ao cdigo informado de Escriturrio."); printf("\n O aumento percentual de 50%%.\n"); break; case 2: printf("\n O cargo correpondente ao cdigo informado de Secretrio."); printf("\n O aumento percentual de 35%%.\n"); break; case 3: printf("\n O cargo correpondente ao cdigo informado de Caixa."); printf("\n O aumento percentual de 20%%.\n"); break; case 4: printf("\n O cargo correpondente ao cdigo informado de Gerente"); printf("\n O aumento percentual de 10%%.\n"); break; case 5: printf("\n O cargo correpondente ao cdigo informado de Diretor"); printf("\n O aumento percentual de 0%%. \n"); break; } system ("pause"); }
C
#include <stdio.h> #include <string.h> struct Student{ int rollno; char name[30]; int age; }; int main(int argc, char *argv[]){ FILE *f; char* filename; filename = argv[1]; f = fopen(filename, "r"); int i=0; struct Student s[5]; for(i=0;i<5;i++){ fscanf(f, "%d,%[^,],%d\n",&s[i].rollno,s[i].name,&s[i].age); printf("%d,%s,%d\n",s[i].rollno,s[i].name,s[i].age); } fclose(f); }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> //The format of data generated by gensort is 100B per record, and each record has first 10 bytes as the real distict value, and the rest as //record ID and some tabs, we only need to compare the first 10 values //So we set the struct below to define each record and sepeate the real value for easily comparison struct arg { char val[10]; char id[90]; }; void readChunk(long num_chunks); void mergeSort(struct arg rec[], long low, long high, long length); void merge(struct arg arr[],long low,long mid,long high, long length); int main(int argc, const char * argv[]) { readChunk(atoi(argv[1])); return 0; } //read chunk records into file and use merge sort to sort void readChunk(long num_chunks) { char buffer[20]; snprintf(buffer, 20, "%ld", num_chunks+1); FILE *newfp = fopen(buffer, "r+"); // get the size of the data file fseek(newfp, 0L, SEEK_END); double length=ftell(newfp); fseek(newfp, 0L, SEEK_SET); long num_rec = length/100; //copy records into file newfp struct arg *rec = malloc(length); char *str1 = malloc(100); long i; for (i=0; i<num_rec; i++) { fread(str1, 100, 1, newfp); memcpy(rec[i].val, str1, 10); memcpy(rec[i].id, str1+12, 90); } fclose(newfp); //run merge sort mergeSort(rec, 0, num_rec-1, length); snprintf(buffer,20, "%ld", num_chunks+1); newfp = fopen(buffer, "w"); for (i=0; i<num_rec; i++) fprintf(newfp, "%.10s %s", rec[i].val, rec[i].id); fclose(newfp); } void mergeSort(struct arg rec[], long low, long high, long length){ if (low < high) { long mid = (low+high)/2; mergeSort(rec, low, mid, length); mergeSort(rec, mid+1, high, length); merge(rec, low, mid, high, length); } } void merge(struct arg arr[],long low,long mid,long high, long length) { long k=low; struct arg *tmp = malloc(length); while(k<=high){ strncpy(tmp[k].val,arr[k].val,10); strncpy(tmp[k].id,arr[k].id,90); k++; } long m=mid+1; long i=low; long j=low; while(j<=mid&&m<=high){ if (strcmp(tmp[j].val,tmp[m].val) <= 0) { strncpy(arr[i].val, tmp[j].val, 10); strncpy(arr[i].id, tmp[j].id, 90); j++; } else{ strncpy(arr[i].val, tmp[m].val, 10); strncpy(arr[i].id, tmp[m].id, 90); m++; } i++; } k=j; while(j<=mid&&k<=mid){ strncpy(arr[i].val,tmp[k].val,10); strncpy(arr[i].id,tmp[k].id,90); i++; k++; } k=m; while(j>mid&&k<=high){ strncpy(arr[i].val,tmp[k].val,10); strncpy(arr[i].id,tmp[k].id,90); i++; k++; } }
C
#include <stdio.h> #include <stdlib.h> int cmp_int(const void * p1, const void * p2) { int x = *(int*)p1; int y = *(int*)p2; if (x == y) return 0; int x1 = x % 10; int y1 = y % 10; if (x1 < y1) return -1; else if (x1 > y1) return 1; else { int a = (x - x1) / 10; void * pp1 = &a; int b = (y - y1) / 10; void * pp2 = &b; return cmp_int (pp1, pp2); } } int main() { int n; scanf ("%d", &n); int * a = calloc (n, sizeof(int)); for (int i = 0; i < n; i++) { scanf ("%d", a + i); } qsort (a, n, sizeof (int), cmp_int); for (int i = 0; i < n; i++) { printf ("%d ", a[i]); } free (a); return 0; }
C
#include <stdio.h> #include <stdlib.h> /* 如何做到手写排序,技巧和必须要背的知识点 首先冒泡排序思想(我们将较大的数向后移动) 循环遍历第一次(0->len): 最大的移到下标为len处 第二次(0->len-1):最大的移到下标为len-1 第三次(0->len-2):最大的移到下标为len-2 第len次(0->1):最大的移动到下标为1 */ void bubble_sort(int arr[], int len){ for (; 1 < len; len--) { for (int i = 0; i < len; ++i) { /* 内循环 做比较移动 */ if (arr[i+1]<arr[i]) { int temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; /* code */ } } } } // void swap(*arr,old,new){ // } /* 定义一个宏 求数组的长度*/ #define GET_ARRAY_LEN(arr,len){len=sizeof(arr)/sizeof(arr[0]);} int main(int argc, char const *argv[]) { int arr[]={1,22,34,45,656,3,23,45,12}; int len; GET_ARRAY_LEN(arr,len) bubble_sort(arr,len); printf("++++++++++++++++++++++++++++\n"); for (int i = 0; i < len; ++i) { printf("%d\n",arr[i] ); } return 0; }
C
#include <stdio.h> #define DEBUG_LEVEL 1 #if(DEBUG_LEVEL==2) #define dprintf(fmt,arg...) printf(fmt,##arg) #define ddprintf(fmt,arg...) printf(fmt,##arg) #elif(DEBUG_LEVEL==1) #define dprintf(fmt,arg...) printf(fmt,##arg) #define ddprintf(fmt,arg...) #else #define dprintf(fmt,arg...) #define ddprintf(fmt,arg...) #endif int main(int argc,char** argv) { int nMeets=0; int nMeetsArranged=0; int begin[10000]={-1}; int end[10000]={-1}; int roomEnd[10000]={-1}; int nRooms; int arranged[10000/32+1]={0}; int earlyTime=0x7fffffff; #define MEET_TO_INDEX(x) ((x) >> 5) #define MEET_TO_MASK(x) (1 << ((x) & 31)) #define meet_raise(x) (arranged[MEET_TO_INDEX(x)] |= MEET_TO_MASK(x)) #define meet_lower(x) (arranged[MEET_TO_INDEX(x)] &= ~MEET_TO_MASK(x)) #define meet_raised(x)(arranged[MEET_TO_INDEX(x)] & MEET_TO_MASK(x)) freopen("meet.in","r",stdin); scanf("%d",&nMeets); dprintf("%d\n",nMeets); int i,j; for(i=0;i<nMeets;i++){ scanf("%d %d",&begin[i],&end[i]); dprintf("%d %d\n",begin[i],end[i]); } //pangwz: sort first int tmp; for(i=0;i<nMeets;i++){ for(j=i;j<nMeets;j++){ if(begin[i]>begin[j]){ tmp = begin[i]; begin[i] = begin[j]; begin[j] = tmp; tmp = end[i]; end[i] = end[j]; end[j] = tmp; } } } dprintf("after sort--------\n"); for(i=0;i<nMeets;i++){ dprintf("%d %d\n",begin[i],end[i]); } newCycle: ddprintf("---newCycle----------\n"); for(i=0;i<nMeets;i++){ ddprintf("---inCycle-----deal meets:%d,ranged:%s\n",i,meet_raised(i)?"Yes":"No"); if(!meet_raised(i)){ for(j=0;j<nRooms;j++){ ddprintf("---inCycle-----test room:%d,now roomend:%d---\n",j,roomEnd[j]); if(begin[i]>=roomEnd[j]){ ddprintf("---inCycle-----hint room:%d,now roomend:%d---\n",j,roomEnd[j]); break; } } if(j==nRooms){ nRooms++; ddprintf("---inCycle-----new room:%d,now roomend:%d---\n",j,roomEnd[j]); } roomEnd[j]=end[i]; meet_raise(i); dprintf("--range meet:%d,room:%d,end:%d\n",i,j,end[i]); goto newCycle; } } #if 1 for(i=0;i<nMeets;i++){ if(meet_raised(i)) ddprintf("meet:%d,raised\n",i); else ddprintf("meet:%d,not raised\n",i); } #endif printf("rooms:%d\n",(nRooms)); return 0; }
C
#include <stdio.h> #include <math.h> #ifndef M_PI #define M_PI 3.141592 #endif #define RAD2DEG M_PI/360.0*2.0 #define DEG2RAD 360.0/M_PI/2.0 int main() { printf("Convert radians to degrees: %f\n",RAD2DEG); printf("Convert degrees to radians: %f\n",DEG2RAD); return(0); }
C
/** * Usage: * #define LOG_LEVEL LOG_LEVEL_XXX * #include "logger.h" */ #ifndef __LOGGER_H__ #define __LOGGER_H__ #include <stdio.h> #include "Std_Types.h" #include "Termio.h" #include "ucos_ii.h" enum { LOG_LEVEL_TRACE = 0, LOG_LEVEL_VERBOSE = 1, LOG_LEVEL_DEBUG = 2, LOG_LEVEL_INFO = 3, LOG_LEVEL_WARN = 4, LOG_LEVEL_ERROR = 5, LOG_LEVEL_OFF = 6, LOG_LEVEL_T = LOG_LEVEL_TRACE, LOG_LEVEL_V = LOG_LEVEL_VERBOSE, LOG_LEVEL_D = LOG_LEVEL_DEBUG, LOG_LEVEL_I = LOG_LEVEL_INFO, LOG_LEVEL_W = LOG_LEVEL_WARN, LOG_LEVEL_E = LOG_LEVEL_ERROR, }; //#undef LOG_LEVEL #ifndef LOG_LEVEL #define LOG_LEVEL LOG_LEVEL_OFF #endif char get_log_string(uint8 level); #if defined(__PCLINT__) #define LOG(lvl, args) #define LOGNH(lvl, args) #elif defined(__HC12__) #pragma push #pragma MESSAGE DISABLE C4000 //Condition always false #define LOG(lvl, args) if (LOG_LEVEL_##lvl >= LOG_LEVEL) { \ (void)printf("[%c:%ld][%s(%d)]:", get_log_string(LOG_LEVEL_##lvl), OSTimeGet(), strrchr(__FILE__, '\\') + 1, (uint16)__LINE__); \ (void)print##args; \ TERMIO_PutChar('\n'); \ } #define LOGNH(lvl, args) if (LOG_LEVEL_##lvl >= LOG_LEVEL) { (void)print##args; } #pragma pop #elif defined(__MINGW32__) #include <stdio.h> #define f(fmt, args...) fprintf(stderr, fmt, ##args) #define LOG(lvl, fmt) if (LOG_LEVEL_##lvl >= LOG_LEVEL) { \ (void)fprintf(stderr, "[%c:%ld][%s.%s(%d)]:", get_log_string(LOG_LEVEL_##lvl), OSTimeGet(), strrchr(__FILE__, '\\') + 1, __func__, (uint16)__LINE__); \ (void)fmt; \ (void)fprintf(stderr, "\n"); \ (void)fflush(stderr); \ } #define LOGNH(lvl, fmt) if (LOG_LEVEL_##lvl >= LOG_LEVEL) { (void)fmt; } #else #define f(fmt, args...) printf(fmt, ##args) #define LOG(lvl, fmt) if (LOG_LEVEL_##lvl >= LOG_LEVEL) { \ (void)printf("[%c:%ld][%s.%s(%d)]:", get_log_string(LOG_LEVEL_##lvl), OSTimeGet(), strrchr(__FILE__, '\\') + 1, __func__, (uint16)__LINE__); \ (void)fmt; \ TERMIO_PutChar('\n'); \ } #define LOGNH(lvl, fmt) if (LOG_LEVEL_##lvl >= LOG_LEVEL) { (void)fmt; } #endif // defined(__HC12__) #endif
C
/***************************************************************************** * mycomplex.c * * DESCRIPTION * This file contains some functions for computing complex numbers. * * HISTORY * 2/2007 Arthur Taylor (MDL): Commented * * NOTES ****************************************************************************/ #include <stdio.h> #include <math.h> #include "mycomplex.h" /* Since _IS_C99_ is set, used here, and then unset in mycomplex.h, we need * to also set it here. */ #ifdef __STDC_VERSION__ #if (__STDC_VERSION__ == 199901L) /* Is c99, so complex.h should exist */ #define _IS_C99_ #endif #endif /***************************************************************************** * myCset() -- Arthur Taylor / MDL * * PURPOSE * Sets a complex number to the given real and imaginary parts. * * ARGUMENTS * x = The real part. (Input) * y = The imaginary part. (Input) * * RETURNS: myComplex * The resulting complex number * * HISTORY * 2/2007 AAT (MDL): Commented * * NOTES ****************************************************************************/ myComplex myCset(double x, double y) { myComplex ans; /* The answer to return */ #ifdef _IS_C99_ /* http://www.gnu.org/software/libc/manual/html_node/Complex-Numbers.html * To construct complex numbers you need a way to indicate the imaginary * part of a number. There is no standard notation for an imaginary * floating point constant. Instead, complex.h defines two macros that can * be used to create complex numbers. */ /* Macro: const float complex _Complex_I */ ans = x + _Complex_I * y; /* ans = x; __imag__ ans = y; */ #else ans.x = x; ans.y = y; #endif return ans; } /***************************************************************************** * myCprint() -- Arthur Taylor / MDL * * PURPOSE * Prints a complex number. * * ARGUMENTS * z = The complex number to print. (Input) * * RETURNS: void * * HISTORY * 2/2007 AAT (MDL): Commented * * NOTES ****************************************************************************/ void myCprint(myComplex z) { #ifdef _IS_C99_ printf("Real = %10.7f, Imag = %10.7f\n", __real__ z, __imag__ z); #else printf("Real = %10.7f, Imag = %10.7f\n", z.x, z.y); #endif } #ifndef _IS_C99_ /***************************************************************************** * myCreal (Macro for my_Creal()) -- Arthur Taylor / MDL * * PURPOSE * Returns the real part of a complex number. * * ARGUMENTS * z = The complex number of interest. (Input) * * RETURNS: double * Real(z) * * HISTORY * 2/2007 AAT (MDL): Commented * * NOTES ****************************************************************************/ double my_Creal(myComplex z) { return (z.x); } /***************************************************************************** * myCimag (Macro for my_Cimag()) -- Arthur Taylor / MDL * * PURPOSE * Returns the imaginary part of a complex number. * * ARGUMENTS * z = The complex number of interest. (Input) * * RETURNS: double * Imag(z) * * HISTORY * 2/2007 AAT (MDL): Commented * * NOTES ****************************************************************************/ double my_Cimag(myComplex z) { return (z.y); } /***************************************************************************** * myCadd (Macro for my_Cadd()) -- Arthur Taylor / MDL * * PURPOSE * Adds two complex numbers. * * ARGUMENTS * z1 = The first complex number to add. (Input) * z2 = The second complex number to add. (Input) * * RETURNS: myComplex * z1 + z2. * * HISTORY * 2/2007 AAT (MDL): Commented * * NOTES ****************************************************************************/ myComplex my_Cadd(myComplex z1, myComplex z2) { z1.x += z2.x; z1.y += z2.y; return z1; } /***************************************************************************** * myCsub (Macro for my_Csub()) -- Arthur Taylor / MDL * * PURPOSE * Subtracts two complex numbers. * * ARGUMENTS * z1 = The complex number to subtract from. (Input) * z2 = The complex number to subtract. (Input) * * RETURNS: myComplex * z1 - z2. * * HISTORY * 2/2007 AAT (MDL): Commented * * NOTES ****************************************************************************/ myComplex my_Csub(myComplex z1, myComplex z2) { z1.x -= z2.x; z1.y -= z2.y; return z1; } /***************************************************************************** * myCmul (Macro for my_Cmul()) -- Arthur Taylor / MDL * * PURPOSE * Multiplies two complex numbers. * * ARGUMENTS * z1 = The first complex number to multiply. (Input) * z2 = The second complex number to multiply. (Input) * * RETURNS: myComplex * z1 * z2. * * HISTORY * 2/2007 AAT (MDL): Commented * * NOTES ****************************************************************************/ myComplex my_Cmul(myComplex z1, myComplex z2) { myComplex ans; /* The answer to return */ ans.x = z1.x * z2.x - z1.y * z2.y; ans.y = z1.x * z2.y + z1.y * z2.x; return ans; } /***************************************************************************** * myCmul_Real (Macro for my_Cmul_Real()) -- Arthur Taylor / MDL * * PURPOSE * Multiplies a complex times a real number. * * ARGUMENTS * z = The complex number to multiply. (Input) * a = The real number to multiply. (Input) * * RETURNS: myComplex * z * a. * * HISTORY * 2/2007 AAT (MDL): Commented * * NOTES ****************************************************************************/ myComplex my_Cmul_Real(myComplex z, double a) { z.x *= a; z.y *= a; return z; } /***************************************************************************** * myCinv (Macro for my_Cinv()) -- Arthur Taylor / MDL * * PURPOSE * The multiplicative inverse of a complex number. * * ARGUMENTS * z = The complex number to take the inverse of. (Input) * * RETURNS: myComplex * 1 / z. * * HISTORY * 2/2007 AAT (MDL): Commented * * NOTES * Don't want to prevent division by zero since C99 didn't. ****************************************************************************/ myComplex my_Cinv(myComplex z) { myComplex ans; /* The answer to return */ double r2; /* The magnitude (squared) of z */ /* Don't want to prevent division by zero since C99 didn't. */ r2 = (z.x * z.x + z.y * z.y); ans.x = z.x / r2; ans.y = -1 * z.y / r2; return ans; } /***************************************************************************** * myCexp (Macro for my_Cexp()) -- Arthur Taylor / MDL * * PURPOSE * Computes e raised to a complex number. * * ARGUMENTS * z = The complex number to raise e to. (Input) * * RETURNS: myComplex * e to the z power * * HISTORY * 2/2007 AAT (MDL): Commented * * NOTES * Don't want to prevent division by zero since C99 didn't. ****************************************************************************/ myComplex my_Cexp(myComplex z) { myComplex ans; /* The answer to return */ double e_x; /* The exponential of the real part of z */ e_x = exp(z.x); ans.x = e_x * cos(z.y); ans.y = e_x * sin(z.y); return ans; } /***************************************************************************** * myClog (Macro for my_Clog()) -- Arthur Taylor / MDL * * PURPOSE * Computes the base e logarithm of a complex number. * * ARGUMENTS * z = The complex number to compute the base e logarithm of. (Input) * * RETURNS: myComplex * log(e) (z) * * HISTORY * 2/2007 AAT (MDL): Commented * * NOTES ****************************************************************************/ myComplex my_Clog(myComplex z) { myComplex ans; /* The answer to return */ ans.x = 0.5 * log(z.x * z.x + z.y * z.y); ans.y = atan2(z.y, z.x); return ans; } /***************************************************************************** * myCsqrt (Macro for my_Csqrt()) -- Arthur Taylor / MDL * * PURPOSE * Computes the square root of a complex number. * * ARGUMENTS * z = The complex number to compute the square root of. (Input) * * RETURNS: myComplex * sqrt(z) * * HISTORY * 2/2007 AAT (MDL): Commented * * NOTES ****************************************************************************/ myComplex my_Csqrt(myComplex z) { myComplex ans; /* The answer to return */ double r; /* The magnitude of z */ r = sqrt(z.x * z.x + z.y * z.y); ans.x = sqrt((z.x + r) / 2.0); if (z.y >= 0) { ans.y = sqrt((r - z.x) / 2.0); } else { ans.y = -1 * sqrt((r - z.x) / 2.0); } return ans; } #endif /***************************************************************************** * main() (Private) -- Arthur Taylor / MDL * * PURPOSE * Used to test the implementation of complex. * * ARGUMENTS * argc = The number of command line arguments (ignored). (Input) * argv = The command line arguments (ignored). (Input) * * RETURNS: int * 0 * * HISTORY * 2/2007 AAT (MDL): Commented * * NOTES ****************************************************************************/ #ifdef DEBUG_MYCOMPLEX #include <time.h> int main(int argc, char **argv) { myComplex z1, z2; /* Temporary variables for testing */ myComplex z3, z4; /* Temporary variables for testing */ myComplex z5, z6; /* Temporary variables for testing */ int i; /* index counter for testing computation time. */ #ifdef _IS_C99_ printf("Is C99\n"); printf("sizeof(myComplex) = %d\n", sizeof(myComplex)); #else printf("Is not C99\n"); printf("sizeof(myComplex) = %d\n", sizeof(myComplex)); #endif z1 = myCset(0, 1); z2 = myCset(1, 1); myCprint(z1); printf("using Creal Cimag %f %f\n", myCreal(z1), myCimag(z1)); myCprint(z2); printf("using Creal Cimag %f %f\n", myCreal(z2), myCimag(z2)); z3 = myCadd(z1, z2); z3 = myCadd(z3, z2); z4 = myCadd(z1, myCmul_Real(z2, 2)); printf("Testing addition:\n"); myCprint(z3); myCprint(z4); z3 = myCsub(z3, myCmul_Real(z2, 2)); printf("Testing subtraction:\n"); myCprint(z3); myCprint(z1); z3 = z4; z5 = myCmul(z3, z4); z6 = myCmul(z3, myCinv(myCinv(z4))); printf("Testing multiplication and inverse:\n"); myCprint(z5); myCprint(z6); z3 = myCexp(z5); z4 = myCexp(myClog(myCexp(z6))); printf("Testing Exponential:\n"); myCprint(z3); myCprint(z4); z5 = myCsqrt(z3); z6 = myCsqrt(myCsqrt(myCmul(z4, z4))); printf("Testing square root:\n"); myCprint(z5); myCprint(z6); printf("Testing inv(0+i0):\n"); z3 = myCset(0, 0); myCprint(z3); z3 = myCinv(z3); myCprint(z3); printf("Starting speed test (diff between -ansi and -std=c99)\n"); printf("Timing info. %f\n", clock() / (double)(CLOCKS_PER_SEC)); for (i = 0; i < 200000; ++i) { z1 = myCset(0, 1); z2 = myCset(1, 1); z3 = myCadd(z1, z2); z3 = myCadd(z3, z2); z4 = myCadd(z1, myCmul_Real(z2, 2)); z3 = myCsub(z3, myCmul_Real(z2, 2)); z3 = z4; z5 = myCmul(z3, z4); z6 = myCmul(z3, myCinv(myCinv(z4))); z3 = myCexp(z5); z4 = myCexp(myClog(myCexp(z6))); z5 = myCsqrt(z3); z6 = myCsqrt(myCsqrt(myCmul(z4, z4))); z3 = myCset(0, 0); z3 = myCinv(z3); } printf("Timing info. %f\n", clock() / (double)(CLOCKS_PER_SEC)); return 0; } #endif
C
/*****************************************a2.c********************************************* Student Name: Filip Hasson                   Student Number:  0878596 Date: 02/13/2015                         Course Name: CIS 2500 I have exclusive control over this submission via my password. By including this statement in this header comment, I certify that:      1) I have read and understood the University policy on academic integrity;      2) I have completed the Computing with Integrity Tutorial on Moodle; and      3) I have achieved at least 80% in the Computing with Integrity Self Test. I assert that this work is my own. I have appropriately acknowledged any and all material (data, images, ideas or words) that I have used, whether directly quoted or paraphrased. Furthermore, I certify that this assignment was prepared by me specifically for this course. *******************************************************************************************/ #include "functions.h" int main (void) { int x = 0; int parsedVal=0; int parsedVal2=0; int penUp=0; int lines=0; int hide=0; char printBuffer[100][255]; char part1[98]; char part2[98]; char part3[98]; char save='n'; FILE *file; cursorT * cursPtr=malloc(sizeof(cursorT)); if (cursPtr==NULL) { mvprintw (46,1,"There is not enough memory to run the program!"); }; cursPtr->locX =48; cursPtr->locY =22; cursPtr->dir =0; cursPtr->color =1; initscr(); start_color(); init_pair(1, COLOR_WHITE,COLOR_WHITE); init_pair(2, COLOR_WHITE,COLOR_BLACK); init_pair(3, COLOR_BLUE,COLOR_BLACK); init_pair(4, COLOR_RED,COLOR_BLACK); init_pair(5, COLOR_YELLOW,COLOR_BLACK); init_pair(6, COLOR_GREEN,COLOR_BLACK); attron(COLOR_PAIR(1)); for (x = 0; x < 100; x++) { mvaddch(0,x,' '); mvaddch(44,x,' '); mvaddch(54,x,' '); } for (x = 0; x <55; x++) { mvaddch(x,0,' '); mvaddch(x,100,' '); } attron(COLOR_PAIR(2)); while (strcmp(part1,"quit")!=0) { attron(COLOR_PAIR(2)); strcpy(part1,""); strcpy(part2,""); strcpy(part3,""); drawCursor (*cursPtr); if (hide==1) mvaddch(cursPtr->locY,cursPtr->locX,' '); attron(COLOR_PAIR(2)); move(45,1); scanw ("%s %s %s",part1,part2,part3); strcpy (printBuffer[lines],part1); strcat (printBuffer[lines]," "); strcat (printBuffer[lines],part2); lines++; clearUserText (); clearMessageText(); refresh(); if (strcmp (part1,"setpencolor")==0) { if (strcmp(part2,"blue")==0) cursPtr->color=1; else if (strcmp(part2,"red")==0) cursPtr->color=2; else if (strcmp(part2,"yellow")==0) cursPtr->color=3; else if (strcmp(part2,"green")==0) cursPtr->color=4; else mvprintw (47,1,"Please only enter blue, red, yellow or green as a color"); refresh(); } else if (strcmp(part1,"fd")==0) { parsedVal = atoi(part2); if (parsedVal <= 0) mvprintw (47,1,"Please Enter A Positive Number"); else forward (cursPtr, parsedVal, penUp); } else if (strcmp(part1,"bk")==0) { parsedVal = atoi(part2); if (parsedVal <= 0) mvprintw (47,1,"Please Enter A Positive Number"); else back (cursPtr,parsedVal,penUp); } else if (strcmp(part1,"rt")==0) { parsedVal = atoi(part2); if (parsedVal <= 0) mvprintw (47,1,"Please Enter A Positive Number"); else if (parsedVal != 30 && parsedVal != 90 && parsedVal != 45) mvprintw (47,1,"Please only use 30 and 90 degree values"); else rotateRight(cursPtr,parsedVal); } else if (strcmp (part1,"lt")==0) { parsedVal = atoi (part2); if (parsedVal <=0) mvprintw (47,1,"Please Enter A Positive Number"); else if (parsedVal != 30 && parsedVal != 90 && parsedVal != 45) mvprintw (47,1,"Please only use 30 and 90 degree values"); else rotateLeft(cursPtr,parsedVal); } else if (strcmp (part1,"pd")==0) { penUp=0; } else if (strcmp (part1,"pu")==0) { penUp=1; } else if (strcmp (part1,"quit")==0) { clearMessageText(); mvprintw (47,1,"Would you like to save your code? y/n "); save = getch(); if (save == 'y' || save == 'Y') { file = fopen("code.logo","w+"); for (x=0;x<=lines;x++) { fprintf(file,"%s\n",printBuffer[x]); } } else mvprintw(47,1,"Thank you for playing! "); } else if (strcmp (part1,"ht")==0) hide=1; else if (strcmp (part1,"st")==0) hide=0; else if (strcmp (part1,"setxy")==0) { parsedVal = atoi (part2); parsedVal2 = atoi (part3); if (parsedVal >99 || parsedVal2 >43 || parsedVal==0 || parsedVal2==0) mvprintw (47,1,"Sorry this would take you out of the drawing board!"); else if (parsedVal >0 && parsedVal2 >0) { mvaddch (cursPtr->locY,cursPtr->locX,' '); cursPtr->locX=parsedVal; cursPtr->locY=parsedVal2; } else mvprintw(47,1,"Please enter command as: setxy <x value> <y value>"); } else if (strcmp (part1,"clean")==0) clean(); else if (strcmp (part1,"home")==0) { cursPtr->locX=48; cursPtr->locY=22; } else mvprintw (47,1,"Please only enter a valid logo command"); refresh(); } file = fopen("assets/code.txt","w+"); for (x=0;x<=lines;x++) { fprintf(file,"%s\n",printBuffer[x]); } fclose(file); getch(); free(cursPtr); endwin(); return 0; }
C
#define _GNU_SOURCE #include <stdio.h> #include <pthread.h> #include <time.h> #include <stdlib.h> #include <unistd.h> #define NT 10 #define SIZE 100 pthread_mutex_t mutex; int matriz[SIZE][NT]; int inicializa_matriz(){ int i, j; for(i=0;i<SIZE;i++) for(j=0;j<NT;j++) matriz[i][j] = rand()%100; return 0; } void* soma_coluna(void *p) { int i, soma=0; pthread_mutex_lock(&mutex); for(i=0;i<SIZE;i++){ printf("THREAD#%d: Calculando SOMA=%d\n", (int)(size_t)p, soma); soma += matriz[i][(int)(size_t)p]; } pthread_mutex_unlock(&mutex); printf("THREAD#%d: Finalizou. SOMA=%d\n", (int)(size_t)p, soma); pthread_exit(NULL); } int main(int argc, char **argv) { int i; pthread_t tid[SIZE]; srand(time(NULL)); inicializa_matriz(); pthread_mutex_init(&mutex, NULL); for(i=0;i<NT;i++) pthread_create(&tid[i], NULL, soma_coluna, (void *)(size_t) i); for(i=0;i<NT;i++) pthread_join(tid[i], NULL); pthread_mutex_destroy(&mutex); return 0; }
C
int removeDuplicates(int* nums, int numsSize){ if(numsSize==1) return numsSize; if(numsSize==0) return 0; int delete=0; int last=nums[0]; for(int i=1;i<numsSize;++i){ if(nums[i]==last){ delete++; }else{ last=nums[i]; nums[i-delete]=nums[i]; } } return numsSize-delete; }
C
#include <assert.h> #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include "benchmark.h" #include "board.h" #include "board2eps.h" #include <inttypes.h> #include "search.h" #include "stats.h" #include "ucitable.h" #include "parser.h" #include "eval.h" #include "ttable.h" static void print_board(Board *b) { puts("{"); printf(" \"code\": \"%" PRIu64 "\",\n", b->code); printf(" \"winner\": %d,\n", (b->winner + 1) % 3); puts(" \"pieces\": ["); for (int c = 0; c < NUM_COLS; c++) { if (c) { puts(","); } fputs(" [", stdout); for (int r = 0; r < NUM_ROWS; r++) { if (r) { fputs(",", stdout); } Player p = board_get(b, r, c); if (p == WHITE) { printf("%d", 1); } else if (p == BLACK) { printf("%d", 2); } else { printf("%d", 0); } } fputs("]", stdout); } puts("]"); fputs("}", stdout); } static void print_next_positions(Board *b) { puts("["); for (int c = 0; c < NUM_COLS; c++) { if (c) { puts(","); } if (board_column_full(b, c) || (b->winner != NOBODY)) { puts("0"); } else { board_put(b, c); print_board(b); board_undo(b, c); } } fputs("]", stdout); } static void print_response(Board *b) { puts("{"); fputs("\"current\": ", stdout); print_board(b); puts(","); fputs("\"next\": ", stdout); print_next_positions(b); puts("}"); } int main(int argc, char** argv) { if (argc != 3) { return (EXIT_FAILURE); } Board b; board_init(&b); uint64_t code = strtoull(argv[2], NULL, 10); board_decode(&b, code); if (!strcmp(argv[1], "get")) { print_response(&b); return (EXIT_SUCCESS); } else if (!strcmp(argv[1], "move")) { if (b.winner == NOBODY && !board_full(&b)) { Variation var; variation_init(&var); SearchRecord rec; searchrecord_init(&rec); search(&b, &var, &rec); board_put(&b, var.moves[0]); } print_response(&b); return (EXIT_SUCCESS); } else { return (EXIT_FAILURE); } }
C
#include <stdio.h> int main() { int testes, repeat; scanf("%d", &testes); int tamanho, tempo = 1, drawX, drawY, meio; for (repeat = 1; repeat <= testes; repeat ++) { meio = 2; scanf("%d%d", &tamanho, &tempo); printf("Caso %d:\n", repeat); for (drawY = 0; drawY < tamanho * 2; drawY ++) //Desenha o Triângulo { printf("*"); for (drawX = 0; drawX < (tamanho * 2) - 1; drawX ++) { if (drawY == tamanho && meio > 1) //Meio { for (drawX = 0; drawX < (tamanho * 2) - 1; drawX ++) { if (drawX == drawY - 1) { printf("*"); } else { printf(" "); } } meio --; } else if ((drawX == drawY + (meio - 2) || drawX == (tamanho * 2) - (drawY + meio))) //Borda { printf("*"); } else { if (drawY == 0 || drawY == (tamanho * 2) - 1) //Topo { if (drawX % 2 != 0) { printf(" "); } else { printf("*"); } } else { if ((drawY > (tamanho * 2) - (tempo + 2) && (drawX < drawY && drawX >= (tamanho * 2) - (drawY)))) //Tempo Inferior { printf("."); } else { if ((drawY > (tamanho - (tamanho - tempo)) && drawY < tamanho) && (drawX > drawY && drawX < (tamanho * 2) - (drawY + 1))) //Tempo Superior { printf("."); } else { printf(" "); } } } } } if (drawY < (tamanho * 2) - 1) //Baixo { printf("*\n"); } else { printf("*\n"); } } } return(0); }
C
#ifndef INT_ARRAY_H #define INT_ARRAY_H #include <stdio.h> #include <stdlib.h> struct int_array { int *data; int length; int allocated; }; void int_array_init(struct int_array *a); void int_array_add(struct int_array *a, int b); void int_array_printf(struct int_array a, char* format); int int_array_main(int argc, int **argv); #endif
C
#include <stdio.h> #include<stdlib.h> #define MAX_SIZE_PTRARRAY 512 #define MAX_NUM_PTR 512 #define MAX_NUM_INTVAR 512 typedef struct p{ int pos; int times; int data; }ppp; int compare(const void *p1,const void *p2){ ppp *q1=(ppp*)p1,*q2=(ppp*)p2; if(q1->times<q2->times)return -1; if(q1->times>q2->times)return 1; if(q1->data<q2->data)return -1; return 1; } ppp ps[512]; void count(int **p[]){ int ***tmp=p; int count=0; while(tmp[count])tmp[count++]; int *t=**tmp; int index=0; for(int i=0;i<count;i++){ int yes=0; for(int j=0;j<index;j++){ if(ps[j].pos==(int)&(**tmp[i])){ yes=1; ps[j].times++; break; } }if(!yes){ ps[index].pos=(int)&(**tmp[i]); ps[index].data=**tmp[i]; ps[index++].times=1; } }qsort(ps,index,sizeof(ppp),compare); for(int i=0;i<index;i++)printf("%d %d\n",ps[i].data,ps[i].times); } int main(){ int **ptrArray[MAX_SIZE_PTRARRAY] = {}; int *intPtr[MAX_NUM_PTR]; int intVar[MAX_NUM_INTVAR]; intVar[0] = 7; intVar[1] = 6; intVar[2] = 2; intVar[3] = 9; ptrArray[0] = &intPtr[0]; ptrArray[1] = &intPtr[1]; ptrArray[2] = &intPtr[2]; ptrArray[3] = &intPtr[3]; ptrArray[4] = NULL; intPtr[0] = &intVar[0]; intPtr[1] = &intVar[1]; intPtr[2] = &intVar[2]; intPtr[3] = &intVar[3]; count(ptrArray); return 0; }
C
#include <msp430.h> int main(void) { WDTCTL = WDTPW | WDTHOLD; // stop watchdog timer PM5CTL0 &= ~LOCKLPM5; // enables the use of GPIO P1DIR &= ~BIT1; // Makes P1.1 switch an input P1REN |= BIT1; // P1.1 pull up resistor is enabled P1OUT |= BIT1; // P1.1 makes the resistor pull up P1IE |= BIT1; // P1.1 is now the interrupt pin P1DIR |= BIT0; // P1.0 LED is an output P1OUT &= ~BIT0; P2DIR |= BIT0; // P2.0 LED is an output int i1; // counter __enable_interrupt(); while(1) { if(i1 > 10000) // the speed of the blink { P2OUT ^= BIT0; // P2.0 LED toggles i1 = 0; // Resets i1 to 0 so i1 can count back up to 10000 } i1++; // the counter is incremented } return 0; } #pragma vector=PORT1_VECTOR //interrupt at Port 1 __interrupt void Port_1(void) { P1OUT ^= BIT0; // Toggles the P1.0 LED P1IFG &= ~BIT1; // Disables the interrupt flag }
C
/* Exercise of the book: Algoritmos e Lgica de Programao (Manzano e Figueiredo) List 01 | Page 57 and 58 | A to Z | Exercise 08 Author: Aldrin Marques Since: 07/09/2020 Function: Write an algorithm that calculates and show the volume of an retangular box Volume = Height * Width * Length . */ #include <stdio.h> #include <stdlib.h> #include <locale.h> void main(){ system("cls"); // Clear the Screen setlocale(LC_ALL, "Portuguese"); // System language in Brazil // Var float vl = 0, le = 0, wi = 0, he = 0; // Input printf("Input the heigth: "); scanf("%f", &he); printf("Input the width: "); scanf("%f", &wi); printf("Input the length: "); scanf("%f", &le); // Operation vl = le*wi*he; // Output printf("the volume is %0.2f cm", vl); }