language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include "unpipc.h" int main(int argc, char **argv) { int fd; struct stat stat; struct door_info info; if (argc != 2) err_quit("usage: doorinfo <pathname>"); fd = Open(argv[1], O_RDONLY); Fstat(fd, &stat); if (S_ISDOOR(stat.st_mode) == 0) err_quit("pathname is not a door"); Door_info(fd, &info); printf("server PID = %ld, uniquifier = %ld", (long) info.di_target, (long) info.di_uniquifier); if (info.di_attributes & DOOR_LOCAL) printf(", DOOR_LOCAL"); if (info.di_attributes & DOOR_PRIVATE) printf(", DOOR_PRIVATE"); if (info.di_attributes & DOOR_REVOKED) printf(", DOOR_REVOKED"); if (info.di_attributes & DOOR_UNREF) printf(", DOOR_UNREF"); printf("\n"); exit(0); }
C
#include <stdio.h> // Declare a global variable int output; int print() { printf("%d\n", output); }
C
/****************************************************************************** * Copyright (C) 2017 by Alex Fosdick - University of Colorado * * Redistribution, modification or use of this software in source or binary * forms is permitted as long as the files maintain this copyright. Users are * permitted to modify this and use it to learn about the field of embedded * software. Alex Fosdick and the University of Colorado are not liable for any * misuse of this material. * *****************************************************************************/ /** * @file <stats.c> * @brief <Embedded Software HW1 > * * This is the 1st HW of the Coursera Course Embedded Software. main() - The main entry point for your program print_statistics() - A function that prints the statistics of an array including minimum, maximum, mean, and median. print_array() - Given an array of data and a length, prints the array to the screen [DONE] find_median() - Given an array of data and a length, returns the median value [DONE] find_mean() - Given an array of data and a length, returns the mean [DONE] find_maximum() - Given an array of data and a length, returns the maximum [DONE] find_minimum() - Given an array of data and a length, returns the minimum [DONE] sort_array() - Given an array of data and a length, sorts the array from largest to smallest. [DONE] (The zeroth Element should be the largest value, and the last element (n-1) should be the smallest value. ) * * @author <Tushar Patil> * @date <11/01/2021> * */ #include <stdio.h> // #include "stats.h" void sort_array(); void print_statistics(int maximum, int minimum, int median, float mean); int find_maximum(); int find_minimum(); int find_median(); float find_mean(); void swap(unsigned char *p, unsigned char *q) { int temp; temp = *p; *p = *q; *q = temp; } /* Size of the Data Set */ #define SIZE (40) void main() { unsigned char test[SIZE] = {34, 201, 190, 154, 8, 194, 2, 6, 114, 88, 45, 76, 123, 87, 25, 23, 200, 122, 150, 90, 92, 87, 177, 244, 201, 6, 12, 60, 8, 2, 5, 67, 7, 87, 250, 230, 99, 3, 100, 90}; /* Other Variable Declarations Go Here */ int maximum = 0, minimum = 0, median = 0; float mean = 0; printf("Embedded Software HW1 \n"); printf("Unsorted array\n"); for(int i =0; i<SIZE; i++) { printf("%d\t", test[i]); } printf("\n"); sort_array(test); printf("Sorted array\n"); for(int i =0; i<SIZE; i++) { printf("%d\t", test[i]); } printf("\n"); maximum= find_maximum(test); minimum= find_minimum(test); median = find_median(test); mean = find_mean(test); /* Statistics and Printing Functions Go Here */ print_statistics(maximum, minimum, median, mean); } /* Add other Implementation File Code Here */ void sort_array(unsigned char test[]) { unsigned char temp = 0; for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { if (test[i] > test[j]) { temp = test[i]; test[i] = test[j]; test[j] = temp; } } } } void print_statistics(int maximum, int minimum, int median, float mean){ printf("Maximum = %d,\t Minimum = %d,\t Median = %d,\t Mean = %.4f\n", maximum, minimum, median, mean); } int find_maximum(unsigned char test[]) { int max = test[0]; for (int i = 1; i < SIZE; i++) { if (test[i] > max) max = test[i]; } return max; } int find_minimum(unsigned char test[]) { int min = test[0]; for (int i = 1; i < SIZE; i++) { if (test[i] < min) min = test[i]; } return min; } int find_median(unsigned char test[]) { for (int i = 0; i < SIZE - 1; i++) { for (int j = 0; j < SIZE - i - 1; j++) { if (test[j] > test[j + 1]) { swap(&test[j], &test[j + 1]); } } } int n = (SIZE + 1) / 2 - 1; return test[n]; } float find_mean(unsigned char test[]) { float mean; int sum = 0; for (int i = 0; i < SIZE; i++) { sum += test[i]; } mean = sum / (float)SIZE; return mean; }
C
// Name: Subham Subhasis Sahoo // Entry No. : 2020CSB1317 #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> // defining node structure to be used in linked lists typedef struct node { int num; struct node *next; } node; // list of linked lists typedef struct node_arr { struct node *head; } node_arr; // initializing all head pointers in the list to null void init_graph(node_arr *graph, int m) { for (int i = 0; i < m; i++) { graph[i].head = NULL; } } // creating a node from given number node *create_node(int num) { node *temp; temp = (struct node *)malloc(sizeof(struct node)); temp->num = num; temp->next = NULL; return temp; } void insert(node_arr *graph, int index, int val, int m) { node *temp = create_node(val); // chaining vertexes that are connected to a particular vertex if (graph[index].head == NULL) { graph[index].head = temp; } else { struct node *p = graph[index].head; while (p->next != NULL) { p = p->next; } p->next = temp; temp->next = NULL; } } void display(node_arr *graph, int m) { // looping through vertexes for (int i = 0; i < m; i++) { struct node *temp = graph[i].head; if (temp == NULL) { printf("\tindex %d:\t---\n", i); } else { printf("\tindex %d:\t", i); struct node *temp = graph[i].head; // looping through vertexes that were connected to the the main vertex while (temp != NULL) { printf("-> %d ", temp->num); temp = temp->next; } printf("\n"); } } } // queue implemented using linked list for DFS algorithm struct node *f = NULL; struct node *r = NULL; // enqueue operation void enqueue(int val) { struct node *n = (struct node *)malloc(sizeof(struct node)); if (n == NULL) { printf("Queue is Full"); } else { n->num = val; n->next = NULL; if (f == NULL) { f = r = n; } else { r->next = n; r = n; } } } // is empty condition int isEmpty() { if (f == NULL) { return 1; } else return 0; } // dequeue operation int dequeue() { int val = -1; struct node *ptr = f; // checking if queue is empty or not if (isEmpty()) { printf("Queue is Empty\n"); } else { f = f->next; val = ptr->num; free(ptr); } return val; } // DFS Algorithm int time = 0; void dfs_visit(node_arr *graph, int i, int color[], int d[], int f[], int p[]) { color[i] = 1; time = time + 1; d[i] = time; struct node *x = graph[i].head; while (x != NULL) { // if node not visited if (color[x->num] == 0) { p[x->num] = i; dfs_visit(graph, x->num, color, d, f, p); } x = x->next; } // node with all adjacent nodes visited marked black color[i] = 2; time = time + 1; f[i] = time; } int d_t[10000]; // temporary array to store discovery time while traversal so that it can be used globally int f_t[10000]; // temporary array to store finished time while traversal so that it can be used globally void dfs(node_arr *graph, int m) { // array to store color // 0 for white // 1 for grey // 2 for black int color[m]; // array to store predcessor int p[m]; // array to store discovery time int d[m]; // array to store finishing time int f[m]; for (int i = 0; i < m; i++) { // initializing color of all nodes to white color[i] = 0; p[i] = -1; } for (int i = 0; i < m; i++) { if (color[i] == 0) { dfs_visit(graph, i, color, d, f, p); } } for (int i = 0; i < m; i++) { printf("index %d : discovery time: %d finished time: %d \n", i, d[i], f[i]); d_t[i] = d[i]; // storing discovery time values in global array so as to use later f_t[i] = f[i]; // storing finished time values in global array so as to use later } } // functions to classify edges as tree,back,forward and cross void edge_visit(node_arr *graph, int i, int color[], int d[], int f[], int p[]) { color[i] = 1; time = time + 1; d[i] = time; struct node *x = graph[i].head; while (x != NULL) { if (color[x->num] == 0) // Tree edge { printf("%d --> %d : Tree edge \n", i, x->num); edge_visit(graph, x->num, color, d, f, p); } else { // condition to check for back edge if (d_t[i] > d_t[x->num] && f_t[i] < f_t[x->num]) { printf("%d --> %d : Back edge \n", i, x->num); } // condition to check for forward edge else if (d_t[i] < d_t[x->num] && f_t[i] > f_t[x->num]) { printf("%d --> %d : Forward edge \n", i, x->num); } else { printf("%d --> %d : Cross edge \n", i, x->num); } } x = x->next; } // node with all adjacent nodes visited marked black color[i] = 2; time = time + 1; f[i] = time; } void edge(node_arr *graph, int m) { // array to store color // 0 for white // 1 for grey // 2 for black int color[m]; // array to store predcessor int p[m]; // array to store discovery time int d[m]; // array to store finishing time int f[m]; for (int i = 0; i < m; i++) { // initializing color of all nodes to white color[i] = 0; p[i] = -1; } for (int i = 0; i < m; i++) { if (color[i] == 0) { edge_visit(graph, i, color, d, f, p); } } } int visited[1000][1000]; // used to print edges of undirected graphs void edge_visit_u(node_arr *graph, int i, int color[], int d[], int f[], int p[]) { color[i] = 1; time = time + 1; d[i] = time; struct node *x = graph[i].head; while (x != NULL) { if (visited[i][x->num] == 0 && visited[x->num][i] == 0) { if (color[x->num] == 0) // Tree edge { visited[i][x->num] = 1; visited[x->num][i] = 1; printf("%d --> %d : Tree edge \n", i, x->num); edge_visit_u(graph, x->num, color, d, f, p); } else { visited[i][x->num] = 1; visited[x->num][i] = 1; // condition to check for back edge if (d_t[i] > d_t[x->num] && f_t[i] < f_t[x->num]) { printf("%d --> %d : Back edge \n", i, x->num); } // condition to check for forward edge else if (d_t[i] < d_t[x->num] && f_t[i] > f_t[x->num]) { printf("%d --> %d : Forward edge \n", i, x->num); } else { printf("%d --> %d : Cross edge \n", i, x->num); } } } x = x->next; } // node with all adjacent nodes visited marked black color[i] = 2; time = time + 1; f[i] = time; } void edge_u(node_arr *graph, int m) { // array to store color // 0 for white // 1 for grey // 2 for black int color[m]; // array to store predcessor int p[m]; // array to store discovery time int d[m]; // array to store finishing time int f[m]; for (int i = 0; i < m; i++) { // initializing color of all nodes to white color[i] = 0; p[i] = -1; } for (int i = 0; i < m; i++) { if (color[i] == 0) { edge_visit_u(graph, i, color, d, f, p); } } } int main() { int m; printf("Enter number of vertices : "); scanf("%d", &m); node_arr *arr = (node_arr *)malloc(m * (sizeof(node_arr))); init_graph(arr, m); int output[m]; int input[m]; for (int i = 0; i < m; i++) { input[i] = 0; output[i] = 0; } int c; printf("----------------------------------------------------\nEnter\n 1 for directed\n 0 for undirected \n----------------------------------------------------\n"); scanf("%d", &c); if (c == 1) { printf("Enter one by one your edges for your directed graph and enter -1 -1 to quit giving inputs \n"); while (1) { int x, y; scanf("%d", &x); scanf("%d", &y); output[x]++; input[y]++; if (x == -1 && y == -1) { printf("Your directed graph is as follows : \n"); display(arr, m); break; } insert(arr, x, y, m); } } if (c == 0) { printf("Enter one by one your edges for your undirected graph and enter -1 -1 to quit giving inputs \n"); while (1) { int x, y; scanf("%d", &x); scanf("%d", &y); output[x]++; output[y]++; if (x == -1 && y == -1) { printf("Your undirected graph is as follows : \n"); display(arr, m); break; } insert(arr, x, y, m); insert(arr, y, x, m); } } dfs(arr, m); printf("\n \n The classification of edges are as following : \n\n"); if (c == 0) { edge_u(arr, m); } else { edge(arr, m); } return 0; }
C
#pragma once #ifndef LBaseLibrary_H_INCLUDED #define LBaseLibrary_H_INCLUDED //----------------------------------------------------// // // // This file just serves as a basis to the rest of // // the language program. Think of it as a Library. // // It hosts the main defines/constants, and the // // structs necessary for the working of it. // // Emanuel//GuardianWorld 2019 // //----------------------------------------------------// //----------------------------------------------------// // // // Bellow are the defines, used for easy writing and // // memorization of the actions defined for the // // library program. // // // //----------------------------------------------------// //Communication Defines/Constants //Before making any changes to the numbers of the constants, verify if the aiAmmountText is set to a higher number than the max number here. #define INTRODUCTION 00 #define WELCOMEBACK 01 #define GREETINGS 02 #define AFFIRMATION 03 #define NEGATION 04 #define GOODBYE 29 #define INVALIDACT 99 //Errors #define NORMAL 00 #define NOLANGFILE 90 #define NOPATH 92 //----------------------------------------------------// // // // Bellow are the structs, used for the storage of // // variables/text in the program's memory. // // It uses linked lists to achieve this without // // static allocation // // // //----------------------------------------------------// typedef struct LC* LanguageCP; //This is the pointer to the linked Cell, aka: The main body of the list. Each phrase/word is stored in a Cell. typedef struct { int aiAmmountText[100]; //Stores the ammount of words into an action, it's the only static list, and needs to be adjusted if the ammount of actions passes the number 100. //The area above is used for random Program phrases. LanguageCP MainUserBranch; //The main user branch of the file LanguageCP user_lmw; // The last main branch word of the user LanguageCP MainAIBranch; //The main AI branch of the cell LanguageCP ai_lmw; // The last main branch word of the AI }LanguageModule; //This struct stores the pointers/Main language Cells for the User, and the Program (nammed AI) typedef struct LC { //This is the main cell, each cell is made of: int action; //An action, defined on this library as a #Define char* word; //A word/phrase, that is allocated dynamically to help preserve space. LanguageCP nextWord; //The pointer to the next cell, used for running the list and getting all the options. }LanguageCell; #endif
C
// // main.c // Triangle // // Created by Listen on 17/3/12. // Copyright © 2017年 Listen. All rights reserved. // #include <stdio.h> float remainingAngle(float a,float b){ float c = 180.0 - (a + b); return c; } int main(int argc, const char * argv[]) { float angleA = 30.0; float angleB = 60.0; float angleC = remainingAngle(angleA,angleB); printf("The third angle is %.2f\n",angleC); return 0; }
C
/* * Input module * * - reads the input in large chunks into a buffer * */ /* data */ static int bsize; static unsigned char buffer[MAXLINE+1 + BUFSIZE+1]; /* functions */ void inputInit() { limit = cp = &buffer[MAXLINE+1]; bsize = -1; lineno = 0; file = NULL; /* refill buffer */ fillbuf(); if (cp >= limit) cp = limit; nextline(); } void nextline() { do { if (cp >= limit) { /* refill buffer */ fillbuf(); if (cp >= limit) cp = limit; if (cp == limit) return; } else lineno++; for (line = (char *)cp; *cp == ' ' || *cp == '\t'; cp++) ; } while (*cp == '\n' && cp == limit); if (*cp = '#') { resynch(); nextline(); } } void fillbuf() { if (bsize == 0) return; if (cp >= limit) cp = &buffer[MAXLINE+1]; else { /* move the tail portion */ int n = limit - cp; unsigned char *s = &buffer[MAXLINE+1] - n; line = (char *)s - ((char *)cp - line); while (cp < limit) *s++ = *cp++; cp = &buffer[MAXLINE+1] - n; } bsize = read(infd, &buffer[MAXLINE+1], BUFSIZE); if (bsize < 0) { error("read error\n"); exit(1); } limit = &buffer[MAXLINE+1+bsize]; *limit = '\n'; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* image.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fdelsing <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/01/16 10:40:07 by fdelsing #+# #+# */ /* Updated: 2018/03/29 20:17:47 by fdelsing ### ########.fr */ /* */ /* ************************************************************************** */ #include <fdf.h> void color(t_param *p) { if (p->img.color.rgba.b == 0) { p->img.color.rgba.r -= 0x5; p->img.color.rgba.g += 0x5; } if (p->img.color.rgba.r == 0) { p->img.color.rgba.g -= 0x5; p->img.color.rgba.b += 0x5; } if (p->img.color.rgba.g == 0) { p->img.color.rgba.b -= 0x5; p->img.color.rgba.r += 0x5; } } void put_pixel(int *add, int i, int j, t_param *p) { i += p->c_x; j += p->c_y; if (j >= 0 && j < WIN_Y && i >= 0 && i <= WIN_X) add[(j * WIN_X) + i] = p->img.color.hex; } void adapt_rot_z(t_point *a, t_point *b, t_param *p) { float depth_z; int buf; depth_z = p->map[p->a.y][p->a.x] * p->f.cos_z; buf = a->x; a->x += (int)((float)a->y * (p->f.sin_z)) + (int)depth_z; a->y -= (int)((float)buf * (p->f.sin_z)) - (int)depth_z; depth_z = p->map[p->b.y][p->b.x] * p->f.cos_z; buf = b->x; b->x += (int)((float)b->y * (p->f.sin_z)) + (int)depth_z; b->y -= (int)((float)buf * (p->f.sin_z)) - (int)depth_z; } void adapt_coord(t_point *a, t_point *b, t_param *p) { float depth_y; float depth_x; depth_y = p->map[p->a.y][p->a.x] * p->f.sin_y; depth_x = p->map[p->a.y][p->a.x] * p->f.sin_x; a->x = (int)((((float)a->x - p->o_x) * p->space_x) * p->f.cos_x) + (int)depth_x; a->y = (int)((((float)a->y - p->o_y) * p->space_y) * p->f.cos_y) + (int)depth_y; depth_y = p->map[p->b.y][p->b.x] * p->f.sin_y; depth_x = p->map[p->b.y][p->b.x] * p->f.sin_x; b->x = (int)((((float)b->x - p->o_x) * p->space_x) * p->f.cos_x) + (int)depth_x; b->y = (int)((((float)b->y - p->o_y) * p->space_y) * p->f.cos_y) + (int)depth_y; adapt_rot_z(a, b, p); } void fill_img(t_param *p) { p->a.y = 0; while (p->a.y <= (p->len_y - 1)) { p->a.x = 0; while (p->a.x <= (p->len_x - 1)) { p->b.x = p->a.x + 1; p->b.y = p->a.y; if (p->b.x < p->len_x && p->b.y < p->len_y) trace(p->a, p->b, p); p->b.x = p->a.x; p->b.y = p->a.y + 1; if (p->b.y < p->len_y) trace(p->a, p->b, p); p->a.x++; } p->a.y++; } mlx_put_image_to_window(p->mlx, p->win, p->img.img, 0, 0); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> void main(){ char x; while(1){ scanf("%s", x); if(x >= '0' && x <= '9'){ printf("X is a digit"); break; } } exit(0); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line_utils.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ybrutout <ybrutout@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/12/17 11:12:22 by ybrutout #+# #+# */ /* Updated: 2021/02/24 12:15:04 by ybrutout ### ########.fr */ /* */ /* ************************************************************************** */ #include "get_next_line.h" char *gnl_strdup(char *save, char c) { char *new_s1; int i; i = 0; while (save[i] != c && save[i]) i++; if (!(new_s1 = malloc(sizeof(char) * i + 1))) { free((void *)save); return (NULL); } i = 0; while (save[i] != c && save[i]) { new_s1[i] = save[i]; i++; } new_s1[i] = 0; return (new_s1); } int gnl_if_free(char *s1, int j, char *s2) { s1[j] = 0; free(s2); if (!s1[0]) { free((void *)s1); return (0); } return (1); } char *gnl_sve(char *save, char c) { int i; int j; char *new_s1; int size; i = 0; j = 0; while (save[i] != c && save[i]) i++; if (save[i] == c) i++; size = ft_strlen(&save[i]); if (!(new_s1 = malloc(sizeof(char) * size + 1))) { free((void *)save); return (NULL); } while (save[i]) { new_s1[j] = save[i]; j++; i++; } i = gnl_if_free(new_s1, j, save); return (i ? new_s1 : 0); } char *gnl_strjoin(char *s1, char *s2) { char *new_s; size_t size; size = ft_strlen(s1) + ft_strlen(s2); if (!(new_s = malloc(sizeof(char) * (size + 1)))) { if (s1) free((void *)s1); free(s2); return (0); } ft_memcpy(new_s, s1, ft_strlen(s1)); ft_memcpy(new_s + ft_strlen(s1), s2, ft_strlen(s2)); free((void *)s1); new_s[size] = '\0'; return (new_s); } size_t ft_strlen(char *s) { size_t i; if (!s) return (0); i = 0; while (s[i]) i++; return (i); }
C
/* kpattgen.h By Kongfa Waroros (2020)(2563) Generating Pattern */ #ifndef __klib_pattgen_h #define __klib_pattgen_h #include <stdlib.h> #include <string.h> #define kpttgn_nullptr NULL #define kpttgn_whcMUL width * height * channel_num #define kpttgn___clearzero_whc kpttgn___clear(buffer, 0, channel_num, width, height) #define kpttgn___clearrgba_whc(col) kpttgn___clear(buffer, col, channel_num, width, height) #define kpttgn___init_buffer kpttgn_b* buffer #define kpttgn___Cmalloc_whc(width, height, channel_num) (buffer = kpttgn___malloc_whc(width, height, channel_num)) typedef unsigned char kpttgn_b; typedef union { unsigned int color; struct rgbaTag { kpttgn_b r; kpttgn_b g; kpttgn_b b; kpttgn_b a; } rgba; struct rgbTag { kpttgn_b r; kpttgn_b g; kpttgn_b b; } rgb; struct gTag { kpttgn_b g; } g; }kpttgn_color; typedef struct { kpttgn_color col; float fac; }kpttgn_colorfac; typedef struct { unsigned int num; kpttgn_colorfac* rampptr; }kpttgn_colorramp; kpttgn_colorramp* kpttgn__colorramp_createwith(kpttgn_colorfac* col, unsigned int size) { kpttgn_colorramp* ramp = malloc(sizeof(kpttgn_colorramp)); if (!ramp) return kpttgn_nullptr; if (col && size) { ramp->rampptr = malloc(sizeof(kpttgn_colorfac) * size); ramp->num = size; for (; size>=0;size--) for (int psize = 3; psize >= 0; psize--) { ramp->rampptr[(size * 4) + psize] = col[psize]; } } else { ramp->num = 0; ramp->rampptr = kpttgn_nullptr; } return ramp; } kpttgn_colorramp* kpttgn__colorramp_create() { return kpttgn__colorramp_createwith(kpttgn_nullptr, 0); } void kpttgn__colorramp_destroy(kpttgn_colorramp* ramp) { if (!ramp) return; free(ramp->rampptr); free(ramp); } void kpttgn__colorramp_clear(kpttgn_colorramp* ramp) { if (!ramp) return; free(ramp->rampptr); ramp->num = 0; ramp->rampptr = kpttgn_nullptr; } kpttgn_colorramp* kpttgn__colorramp_add_once(kpttgn_colorramp* ramp, kpttgn_colorfac col) { if (!ramp) return ramp; kpttgn_colorfac* mem = realloc(ramp->rampptr, (ramp->num + 1) * sizeof(kpttgn_colorfac)); if (!mem) return kpttgn_nullptr; ramp->num++; ramp->rampptr = mem; ramp->rampptr[ramp->num - 1] = col; return ramp; } kpttgn_colorramp* kpttgn__colorramp_add_array(kpttgn_colorramp* ramp, kpttgn_colorfac* col, unsigned int size) { if (!(ramp && size)) return ramp; if (size == 1) return kpttgn__colorramp_add_once(ramp, *col); kpttgn_colorfac* mem = realloc(ramp->rampptr, (ramp->num + size) * sizeof(kpttgn_colorfac)); if (!mem) return kpttgn_nullptr; for (int psize = (int)size - 1; psize >= 0; psize--) { mem[ramp->num + psize] = col[psize]; } ramp->num += size; ramp->rampptr = mem; return ramp; } void kpttgn__colorramp_getatfac(kpttgn_colorramp* ramp, float fac, kpttgn_color* color) { if (!ramp->num) return; for (int i = 0; i < ramp->num; i++) { kpttgn_colorfac* c = ramp->rampptr + (i * sizeof(kpttgn_colorfac)); if (fac < c->fac) { kpttgn_colorfac* pc = ramp->rampptr + (max(0, i - 1) * sizeof(kpttgn_colorfac)); float valueDiff = (pc->fac - c->fac); float fractBetween = (valueDiff == 0) ? 0 : (fac - c->fac) / valueDiff; color->rgba.r = ((pc->col.rgba.r - c->col.rgba.r) * fractBetween + c->col.rgba.r) * 255; color->rgba.g = ((pc->col.rgba.g - c->col.rgba.g) * fractBetween + c->col.rgba.g) * 255; color->rgba.b = ((pc->col.rgba.b - c->col.rgba.b) * fractBetween + c->col.rgba.b) * 255; color->rgba.a = ((pc->col.rgba.a - c->col.rgba.a) * fractBetween + c->col.rgba.a) * 255; return; } } color->rgba.r = (kpttgn_colorfac*)(ramp->rampptr + (ramp->num * sizeof(kpttgn_colorfac)))->col.rgba.r; color->rgba.g = (kpttgn_colorfac*)(ramp->rampptr + (ramp->num * sizeof(kpttgn_colorfac)))->col.rgba.g; color->rgba.b = (kpttgn_colorfac*)(ramp->rampptr + (ramp->num * sizeof(kpttgn_colorfac)))->col.rgba.b; color->rgba.a = (kpttgn_colorfac*)(ramp->rampptr + (ramp->num * sizeof(kpttgn_colorfac)))->col.rgba.a; return; } kpttgn_color kpttgn__make_color(unsigned char r, unsigned char g, unsigned char b, unsigned char a) { kpttgn_color _; _.rgba.r = r; _.rgba.g = g; _.rgba.b = b; _.rgba.a = a; return _; } // AABBGGRR const kpttgn_color kpttgn_color_black = { 0xFF000000 }; const kpttgn_color kpttgn_color_white = { 0xFFFFFFFF }; const kpttgn_color kpttgn_color_red = { 0xFF0000FF }; const kpttgn_color kpttgn_color_green = { 0xFF00FF00 }; const kpttgn_color kpttgn_color_blue = { 0xFFFF0000 }; // https://en.wikipedia.org/wiki/SMPTE_color_bars const kpttgn_color kpttgn_color_smpte_100white = { 0xFFEBEBEB }; const kpttgn_color kpttgn_color_smpte_75white = { 0xFFB4B4B4 }; const kpttgn_color kpttgn_color_smpte_yellow = { 0xFF0CB4B5 }; const kpttgn_color kpttgn_color_smpte_cyan = { 0xFFB4B50D }; const kpttgn_color kpttgn_color_smpte_green = { 0xFF0CB5B7 }; const kpttgn_color kpttgn_color_smpte_magenta = { 0xFFB80FB7 }; const kpttgn_color kpttgn_color_smpte_red = { 0xFF100FB7 }; const kpttgn_color kpttgn_color_smpte_blue = { 0xFFB8100F }; const kpttgn_color kpttgn_color_smpte_black = { 0xFF101010 }; const kpttgn_color kpttgn_colors_smpte[] = { {0xFFEBEBEB},{0xFF0CB4B5},{0xFFB4B50D},{0xFF0CB5B7}, {0xFFB80FB7},{0xFF100FB7},{0xFFB8100F} }; kpttgn_b* kpttgn___clear(kpttgn_b* dst, kpttgn_color val, unsigned int channel_num, unsigned int width, unsigned int height) { if (!dst) return kpttgn_nullptr; unsigned long w = 0; while (w < width * height) { for (unsigned int u = 0; u < channel_num; u++) (dst + (w * channel_num))[u] = ((unsigned char*)&val)[u]; w++; } return dst; } kpttgn_b* kpttgn___malloc_whc(unsigned int width, unsigned int height, unsigned int channel_num) { kpttgn_b* _ = (kpttgn_b*) malloc (width * height * channel_num); if (!_) return kpttgn_nullptr; } kpttgn_b* kpttgn__gen_checker(unsigned int width, unsigned int height, unsigned int channel_num, kpttgn_color even, kpttgn_color odd) { kpttgn___init_buffer; if (!kpttgn___Cmalloc_whc(width, height, channel_num)) return kpttgn_nullptr; kpttgn___clearrgba_whc(even); unsigned int i = 1; while (i < width * height) { for (unsigned int cn = 0; cn < channel_num; cn++) buffer[(i * channel_num) + cn] = ((unsigned char*)&(odd.color))[cn]; if (width % 2 == 0 && (i + ((i % 2 == 0) ? 2 : 1)) % (width) == 0) { if (i % 2 == 0) i += 3; else { ++i; for (unsigned int cn = 0; cn < channel_num; cn++) buffer[(i * channel_num) + cn] = ((unsigned char*)&(odd.color))[cn]; i += 2; } } else i += 2; } return buffer; } kpttgn_b* kpttgn__gen_checker_BW(unsigned int width, unsigned int height, unsigned int channel_num) { return kpttgn__gen_checker(width, height, channel_num, kpttgn_color_black, kpttgn_color_white); } kpttgn_b* kpttgn__gen_smpte_simple_color_7bars(unsigned int width, unsigned int height, unsigned int channel_num) { kpttgn_color wo[] = { kpttgn_color_red ,kpttgn_color_green,kpttgn_color_blue }; kpttgn_colorramp* wow = kpttgn__colorramp_createwith(&(wo), 3); if (!wow) return kpttgn_nullptr; kpttgn___init_buffer; if (!kpttgn___Cmalloc_whc(width, height, channel_num)) return kpttgn_nullptr; unsigned int i = 1; while (i < width * height) { //if ((i + 1) % width == 0) ; kpttgn_color col; kpttgn__colorramp_getatfac(wow, 0.5f, &col); kpttgn__colorramp_getatfac(wow, (float)((i + 1) % width) / (float)width, &col); for (unsigned int cn = 0; cn < channel_num; cn++) buffer[(i * channel_num) + cn] = ((unsigned char*)&(col))[cn]; i++; } kpttgn__colorramp_destroy(wow); return buffer; } #endif
C
#include <stdio.h> main() { int x, y=1, z; printf("introduza um numero para fazer a tabuada: "); scanf(" %d", &x); do{ z=x*y; printf("%d x %d = %d\n", x, y, z); y=y+1; }while (y <= 10); }
C
#include<stdio.h> int main() { int suma = 10, a = 10; float b = 15.5; char c = 'e'; char s[500]; int d; printf("La suma es: %i",suma,"\r"); printf("%i %.1f %c",a,b,c); printf("Entra el valor de la variable a: "); scanf("%i",&d); printf("Entra tu nombre: "); scanf("%s",s); printf("El valor de a es: %i",d); printf("Tu nombre es: %s",s); return 0; }
C
#include <sys/inotify.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <signal.h> #include <linux/limits.h> #include <stdbool.h> extern int errno; volatile bool g_termination_flag = 0; void sig_handler (int sig); int print_event_info (const char * wdir, const struct inotify_event *event); int main (int argc, char *argv[]) { if (argc != 2) { printf("usage: <%s> <tracked directory>\n", argv[0]); return -1; } // signal handler init struct sigaction act = {0}; act.sa_handler = sig_handler; //new handler // do not need sa_sigaction (used with SA_SIGINFO) // do not need to block other signals // do not need special flags // sa_restorer not even in posix int ret = sigaction (SIGINT, &act, NULL); ret |= sigaction (SIGTERM, &act, NULL); if (ret) { perror ("sigaction error"); return -1; } // inotify init int inot = inotify_init (); if (inot == -1) { perror ("can't init inotify instance"); return -1; } int dir_inot = inotify_add_watch (inot, argv[1], IN_CREATE | IN_DELETE | IN_MODIFY | IN_ATTRIB \ | IN_ACCESS | IN_OPEN | IN_DELETE_SELF | IN_MOVE_SELF \ | IN_MOVED_FROM | IN_MOVED_TO | IN_UNMOUNT \ ); if (dir_inot == -1) { perror ("can't add dir to watch list"); return -1; } // main cycle: reporting about events size_t buf_sz = sizeof (struct inotify_event) + NAME_MAX; struct inotify_event *event = (struct inotify_event *) calloc (buf_sz, sizeof (char)); // allocate enough for struct with name[] if (event == NULL) { perror ("can't allocate buffer"); close (dir_inot); close (inot); return -1; } while (1) { if (read (inot, event, buf_sz) == -1) { close (dir_inot); close (inot); free (event); if (g_termination_flag) return 0; perror ("can't read inotify event");; return -1; } print_event_info (argv[1], event); } } void sig_handler (int sig) { g_termination_flag = 1; printf ("\n"); } int print_event_info (const char * wdir, const struct inotify_event *event) { printf ("'%s' : ", wdir); if (event->mask & IN_UNMOUNT) { printf ("fs was unmounted\n"); return 0; } if (event->mask & IN_MOVE_SELF) { printf ("moved\n"); return 0; } if (event->mask & IN_DELETE_SELF) { printf ("deleted\n"); return 0; } if (event->len) { printf ("'%s' ", event->name); if (event->mask & IN_ISDIR) printf ("[dir] "); else printf ("[file] "); } if (event->mask & IN_CREATE) printf ("created"); if (event->mask & IN_DELETE) printf ("deleted"); if (event->mask & IN_MODIFY) printf ("modified"); if (event->mask & IN_ATTRIB) printf ("metadata modified"); if (event->mask & IN_ACCESS) printf ("accessed"); if (event->mask & IN_OPEN) printf ("opened"); if (event->mask & IN_MOVED_FROM) printf ("moved outside"); if (event->mask & IN_MOVED_TO) printf ("moved inside"); printf ("\n"); return 0; }
C
#ifndef STACK_H_INCLUDED #define STACK_H_INCLUDED typedef struct stack Stack; typedef union { void *pointer; int integer; double d; } Object; static int stack_errno; // 0 for success on push/pop/top, 1 for full stack on push, 2 for empty stack on pop/top, unmodified by isEmpty Stack *stack_initialize(unsigned int); Object pop(Stack *); void push(Stack *, Object); Object top(Stack *); int stack_isEmpty(Stack *); #endif
C
#include <stdio.h> #include <math.h> int main() { double a, b, c, D, x1,x2; printf(" ax^2 + bx + c = 0 の係数 a, b, cを入力せよ----> "); scanf("%lf %lf %lf", &a, &b, &c); // (1) if (a == 0 && b == 0) { printf("係数が正しくない\n"); return 1; } // (2) if (a == 0 && b != 0) { printf("一次方程式の解が求まった。\n解は、%lf\n" ,-1 * (c / b)); return 0; } D = b * b - 4 * c; // (3) if (D > 0) { D = sqrt(D); x1 = -1 * b * b + D; x2 = -1 * b * b - D; x1 /= 2 * a; x2 /= 2 * a; printf("2つの実数解が求まった。\n解は、%lf, %lf\n" , x1, x2 ); return 0; } // (4) if (D == 0) { printf("重解が求まった。\n解は、%lf\n" ,-1 * (( b * b ) / 2 * a)); return 0; } // (5) if (D < 0) { printf("この二次方程式は実数解を持たない。\n"); return 0; } return 1; }
C
/** * File Name :print.c */ /** Function: resufun * This function prints the root, pdgm,priority ,category * It takes arguments: root of char array, pdgm of char array ,offset of int type and aux_verb of * char array * Return :void */ /* HEADER FILES */ #include <string.h> #include <stdio.h> #include "./headers/struct.h" #include "./common/analyser/morph_logger.h" extern FILE *log_file; #define FUNCTION "resufun()" /*The function order gives descrption of category-enumerator-file based on feature-enumerator-file*/ extern struct order_info order[MAX_NO_OF_CAT]; extern char fe_info[][INFOSIZE]; /*feature information */ extern int FOR_USER; /* for user friendly output */ extern int ALWAYS_DEFAULT_PARADIGM; /* always choose the default paradigm , even though entry is found in dict */ extern int DEFAULT_PARADIGM; /* neglect when paradigm is found */ void resufun(root,pdgm,offset,aux_verb) char root[WORD_SIZE]; /* root of the word */ char pdgm[SUFFWORDSIZE]; /* paradigm of the word */ int offset; /* offset value */ char aux_verb[SUFFWORDSIZE]; /* auxilary verb */ { char *program_name="print_telugu.c"; // PRINT_LOG(log_file," This function prints the root, pdgm,priority ,category"); /* loop1 to loop5 are for reading characters of category,feature value */ int loop1,loop2,loop3,loop4,loop5; /* length of fe,root not found, number of features */ int len_fe_info,not_found,no_of_features; char category[WORD_SIZE]; /* category of the word */ /* feature and feature value of word */ char feature[MAX_NO_OF_CAT][WORD_SIZE],feature_value[MAX_NO_OF_CAT][WORD_SIZE]; len_fe_info = strlen(fe_info[offset-1]); for(loop1 = 0;((fe_info[offset-1][loop1] != ' ')&&(fe_info[offset-1][loop1] !='\"')&&(fe_info[offset-1][loop1] != '\0'));++loop1) category[loop1] = fe_info[offset-1][loop1]; category[loop1] = '\0'; if(FOR_USER) /* to check for user friendly output for category */ printf("@category: "); printf("%s\n",category); if(FOR_USER) /* to check for user friendly output for root */ printf("@root:@ "); printf("%s\n",root); if(FOR_USER) /* to check for user friendly output for paradigm */ printf("@pdgm:@ "); printf("%s\n",pdgm); /* if(ALWAYS_DEFAULT_PARADIGM || DEFAULT_PARADIGM) { if(FOR_USER) printf("INFO: "); printf("my_pdgm\n");} */ loop2=loop1+1; loop3=0; while(loop2<len_fe_info) /* executes when loop2 lessthan length of fe info */ { /* executes until loop1<len_fe_info && fe_info[offset-1][loop1] != ' ' */ for(loop1=loop2;(loop1<len_fe_info && fe_info[offset-1][loop1] != ' '); loop1++) feature[loop3][loop1-loop2] = fe_info[offset-1][loop1]; feature[loop3][loop1-loop2] = '\0'; loop2=loop1+1; /* executes until loop1<len_fe_info && fe_info[offset-1][loop1] != ' ' */ for(loop1=loop2;(loop1<len_fe_info && fe_info[offset-1][loop1] != ' '); loop1++) feature_value[loop3][loop1-loop2] = fe_info[offset-1][loop1]; feature_value[loop3][loop1-loop2] = '\0'; loop2=loop1+1; loop3++; } no_of_features=loop3; loop4=0; /* executes when order.category and guessed category are same */ while(strcmp(order[loop4].category,category)) loop4++; loop5=0; /* executes when order.feature not null */ while(order[loop4].feature[loop5][0] != '\0') { not_found=1; /* executes until loop3<no_of_features && not_found */ for(loop3=0;(loop3<no_of_features && not_found);loop3++) { /* executes when feature value is not equal to tam */ if(!strcmp(order[loop4].feature[loop5],"tam")) { /* executes when auxilary verb is equal to " " */ if(strcmp(aux_verb,"")) { if(FOR_USER) /* gets user friendly output when FOR_USER is true */ { printf("@%s :",feature[loop3]); printf("%s_",aux_verb); printf("%s@\n",feature_value[loop3]); } else { printf("%s_",aux_verb); printf("%s\n",feature_value[loop3]); } not_found = 0; } else { printf("%s\n",feature_value[loop3]); not_found = 0; } } if(!strcmp(order[loop4].feature[loop5],feature[loop3]) && strcmp(order[loop4].feature[loop5],"tam")) { if(FOR_USER) /* gets user friendly output when FOR_USER is true */ { printf("@%s :",feature[loop3]); printf("%s@\n",feature_value[loop3]); } else printf("%s\n",feature_value[loop3]); not_found = 0; } } if(not_found) /* executes when not_found is true */ { if(FOR_USER) /* gets user friendly output when FOR_USER is true */ printf("@%s :@",order[loop4].feature[loop5]); printf("\n"); } loop5++; } }
C
#include <stdlib.h> #include "lists.h" /** * add_nodeint_end - add node at the end of a list * @head: pointer to the head node pointer * @n: integer for node data initialization * * Return: new node pointer if successful, otherwise NULL */ listint_t *add_nodeint_end(listint_t **head, const int n) { listint_t *new, *temp; new = malloc(sizeof(listint_t)); if (new == NULL) return (NULL); new->n = n; new->next = NULL; if (*head == NULL) *head = new; else { for (temp = *head; temp->next != NULL; temp = temp->next) ; temp->next = new; } return (new); }
C
#include "pid.h" #include "stdlib.h" #include "math.h" void pid_init(PID_Typedef* PID, float kP, float kI, float kD, float out_max, float out_min) { PID->kP = kP; PID->kI = kI; PID->kD = kD; PID->out_max = out_max; PID->out_min = out_min; PID->out = 0; PID->error = 0; PID->last_error = 0; PID->last_last_error = 0; } void pid_tune(PID_Typedef* PID, float kP, float kI, float kD) { PID->kP = kP; PID->kI = kI; PID->kD = kD; } float pid(PID_Typedef* PID, float input, float target) { PID->error = target - input; PID->out += PID->kP * (PID->error - PID->last_error) +PID->kI * PID->error +PID->kD * (PID->error - 2 * PID->last_error + PID->last_last_error); PID->last_last_error = PID->last_error; PID->last_error = PID->error; if(PID->out > PID->out_max) PID->out = PID->out_max; if(PID->out < PID->out_min) PID->out = PID->out_min; //if(input!=0)printf("%d, %d, %f, %f,\r\n", input, target, PID->error, PID->out); return PID->out; }
C
#include <avr32/ap7000.h> #include "led.h" /* The current LED setup. */ int led_setup = 0; /* Set a pointer to the location of PIOC control registers. */ volatile avr32_pio_t *led_pio = &AVR32_PIOC; /* Initialize LED I/O. */ void led_init() { /* Enable the lower eight ports. */ led_pio->per |= 0xff; /* Enable output for the lower eight ports. */ led_pio->oer |= 0xff; } /* Update the LEDs according to 'led_setup'. */ void led_update() { /* Clear the output on the lower eight pins. */ led_pio->codr |= 0xff; /* Set the output of the pins according to 'led_setup'. */ led_pio->sodr = led_setup; } /* Set the value of a specific LED. */ void led_set(int i, int on) { /* Mask and set the values. */ on &= 1; led_setup &= ~(1 << i); led_setup |= (on << i); /* Update the data pins. */ led_update(); } /* Get the state of a specific LED. */ int led_get(int i) { return (led_setup & (1 << i)) != 0; } /* Clear all LEDs. */ void led_clear() { /* Clear the internal state of the LEDs. */ led_setup = 0; /* Update the data pins. */ led_update(); }
C
#pragma once #include <wchar.h> struct Ticket; struct ticketContainer_wcsArrStatus; // Creates an empty tickets table file. void ticketContainer_createDatabaseTable(); // Creates a ticket from an array of 13 wide strings. struct Ticket* ticketContainer_createTicketFromDatabaseRow(wchar_t** data); // Creates an array of 13 wide strings from a ticket. wcsArr points to the array. struct ticketContainer_wcsArrStatus* ticketContainer_wcsArrFromTicket(wchar_t** wcsArr, struct Ticket* ticket); // Deallocates what needs to be deallocated in `wcsArr`. void ticketContainer_cleanUpWcsArr(wchar_t** wcsArr, struct ticketContainer_wcsArrStatus*);
C
#include <stdlib.h> #include <math.h> #include "analisis.h" const int n10 = 0; const int n01 = 1; const int n00 = 2; const int n20 = 3;//vector de momentos const int n02 = 4; const int n11 = 5; const int n30 = 6; const int n12 = 7; const int n21 = 8; const int n03 = 9; //constructores void inicializar_analisis(analisis *a){ a->area = 0; a->perimetro = 0; a->centro = 0; a->diametro_mayor = 0; a->diametro_menor = 0; a->momento = 0; a->b = 0; a->generada = 0; } void generar_analisis(analisis *a, int net, int fil, int col){ if(a->generada > 0) vaciar_analisis(a); a->b = (bector *)malloc(sizeof(bector)); generar(a->b, net, fil, col); a->generada = 1; } void generar_componentes(analisis *a){ int i,j; a->area = (float *) malloc(sizeof(float) * a->b->n_conjuntos); a->centro = (punto *) malloc(sizeof(punto) * a->b->n_conjuntos); a->diametro_mayor = (float *) malloc(sizeof(float) * a->b->n_conjuntos); a->diametro_menor = (float *) malloc(sizeof(float) * a->b->n_conjuntos); a->perimetro = (float *) malloc(sizeof(float) * a->b->n_conjuntos); a->momento = (float **) malloc(sizeof(float *) * a->b->n_conjuntos); for(i=0; i<a->b->n_conjuntos;i++) a->momento[i] = (float *) malloc(sizeof(float) * 7); //Por que hay 7 momentos for(i=0; i<a->b->n_conjuntos ; i++){ a->area[i] = 0.0f; a->centro[i].x = a->centro[i].y = 0; a->diametro_mayor[i] = 0.0f; a->diametro_menor[i] = 0.0f; a->perimetro[i] = 0.0f; for(j=0; j<7; j++) a->momento[i][j] = 0.0f; } a->generada = 2; } //destructor void vaciar_analisis(analisis *a){ int j; if(a->generada > 0){ vaciar(a->b); if(a->generada > 1){ free(a->area); free(a->centro); free(a->diametro_mayor); free(a->diametro_menor); free(a->perimetro); for(j=0; j<a->b->n_conjuntos; j++) free(a->momento[j]); free(a->momento); } } free(a->b); inicializar_analisis(a); } //funciones void obtener_vecinos(gray **image, int i, int j, int max_col, int *vecinos){ vecinos[0] = image[i-1][j]; vecinos[1] = image[i][j-1]; vecinos[2] = image[i-1][j-1]; vecinos[3] = image[i-1][j+1]; } int tiene_vecinos(int *vecinos, int tam){ int ret=0; int i; for(i=0; i<tam;i++) ret+=vecinos[i]; if(ret<=0) return 1; else return 0; } int es_frontera(gray **image, int i, int j){ int suma = 0; suma = image[i+1][j] + image[i-1][j] + image[i][j+1] + image[i][j-1] + image[i+1][j+1] + image[i+1][j-1] + image[i-1][j+1] + image[i-1][j-1]; //Como el color del objeto es negro el valor del pixel es 0 // si al sumar los pixeles vecinos el valor es mayor de cero //uno de los pixeles vecinos es fondo y por lo tanto es un pixel frontera if (suma > 0) { return 1; }else { return 0; } } //propiedades float distancia(punto *centro, int dx, int dy){ float x,y; x = centro->x - dx; y = centro->y - dy; return ((float)sqrt( (x*x)+(y*y) )); } /* float my_pow(int x, int p){ int i; int dev = 1; for(i=0; i<p; i++) dev*=x; return dev*1.0f; } float funct_mom(int x, int y, int p, int q){ return (my_pow(x, p) * my_pow(y, q)); } */ void obtener_propiedades(analisis *a){ int visitados = 0; int i = 0; float max, min, dist; nodo *aux; while(i < a->b->max_val && visitados < a->b->n_conjuntos){ if( a->b->vec[i].ins_c > 0 ){ //Hay objetos en ins_c, el conjunto existe max = 0.0f; min = 999.999f; //area a->area[visitados] = ((a->b->vec[i].ins_c + a->b->vec[i].ins_h)* (1.0f/a->b->fil) * (1.0f/a->b->col)); //perimetro * (1.0f/a->b->fil) * (1.0f/a->b->col) a->perimetro[visitados] = ((a->b->vec[i].ins_c)* (1.0f/a->b->fil) * (1.0f/a->b->col)); //centro a->centro[visitados].x = (a->b->vec[i].sum_x)/(a->b->vec[i].ins_c); a->centro[visitados].y = (a->b->vec[i].sum_y)/(a->b->vec[i].ins_c); //diametros aux = a->b->vec[i].c; while(aux){ dist = distancia(&(a->centro[visitados]), aux->x, aux->y); if(dist>max) max = dist; if(dist<min) min = dist; aux=aux->sig; } a->diametro_mayor[visitados] = max; a->diametro_menor[visitados] = min; visitados++; } i++; } } //analizador, funcion principal void analizar(analisis *a, gray **foto, int fil, int col){ int i, j, k; int vecinos[4]; generar_analisis(a, 100, fil, col); for (i = 4; i < fil-4; i++){ for (j = 4; j < col-4; j++){ if(foto[i][j] == 0){ //Pixel de una figura detectado! //Obtenemos los vecinos //Arriba vecinos[0] = a->b->dev[i-1][j]; //Izquierda vecinos[1] = a->b->dev[i][j-1]; // Diagonal Arriba izquierda vecinos[2] = a->b->dev[i-1][j-1]; // Diagonal arriba derecha vecinos[3] = a->b->dev[i-1][j+1]; if (tiene_vecinos(vecinos, 4)) { //si no tiene vecinos, creamos un nuevo conjunto a->b->n_conjuntos++; a->b->control++; insertar(a->b, i, j, a->b->control, es_frontera(foto, i, j)); }else{ //necesario para gestionar correctamente n_conjuntos a->b->n_conjuntos++; insertar(a->b, i, j, 0, es_frontera(foto, i, j)); for( k = 0; k < 4; k++) if(vecinos[k] > 0) unir(a->b, vecinos[k], a->b->dev[i][j]); } } } } // Foto analizada, pasamos al calculo de propiedades generar_componentes(a); obtener_propiedades(a); //a->b->dev <---- MATRIZ INT RESULTANTE //a->b->n_conjuntos <---- NUMERO DE FIGURAS DETECTADOS //a->area <---- AREAS //a->perimetro <---- PERIMETROS //a->centro <---- CENTROS //a->diametro_mayor <---- DIAMETRO MAYOR //a->diametro_menor <---- DIAMETRO MENOR }
C
/* Hacer un programa que por medio de un menú de opciones nos permita realizar las siguientes acciones: * Ingresar el nombre y el precio unitario de 100 artículos. El precio unitario debe ser mayor que 0 (cero). * Calcular la ganancia del 25 % para cada artículo y mostrar los datos de cada uno. * Indicar cuantos artículos tienen la menor ganancia. * Hacer un listado de los artículos que superen el promedio de la ganancia. Debe aparecer el orden de ingreso. * Salir del programa. */ #include <stdio.h> #include <stdio_ext.h> #include <stdlib.h> #include <ctype.h> #define ARTICULOS 3 #define LONG_NOMBRE 30 #define GANANCIA 0.25f #define SALIDA 'e' void main () { char nombreArticulos[ARTICULOS][LONG_NOMBRE]; float precioUnitarioArticulos[ARTICULOS]; float gananciaArticulos[ARTICULOS]; float acumuladorGanancia; float promedioGanancia; float gananciaMinima; int contadorGananciaMinima; char opcion; int bandera = 0; do { system("clear"); printf("+================= MENU PRINCIPAL ==================+\n"); printf("| a - Ingreso de Articulos |\n"); printf("| b - Listar y calcular ganancia de los Articulos |\n"); printf("| c - Articulos con menor ganancia |\n"); printf("| d - Articulos que superan el promedio de ganancia |\n"); printf("| e - Salir del programa |\n"); printf("+===================================================+\n"); printf(" Elija la opcion deseada: "); __fpurge(stdin); scanf("%c", &opcion); system("clear"); switch (tolower(opcion)) { case 'a': for (int i = 0; i < ARTICULOS; i++) { printf("Ingrese el nombre del articulo %i: ", i+1); __fpurge(stdin); scanf("%s", &nombreArticulos[i]); do { printf("Ingrese el precio unitario de %s: ", &nombreArticulos[i]); scanf("%f", &precioUnitarioArticulos[i]); } while (precioUnitarioArticulos[i] <= 0); system("clear"); } bandera = 1; break; case 'b': if(bandera == 0) { printf("Cargue los registros de los articulos primero.\n"); } else { acumuladorGanancia = 0; printf("============== LISTADO DE ARTICULOS Y GANANCIA ==============\n"); for (int i = 0; i < ARTICULOS; i++) { //Calculo de la ganancia desde el precio unitario gananciaArticulos[i] = precioUnitarioArticulos[i] * GANANCIA; acumuladorGanancia += gananciaArticulos[i]; //Obtencion del valor de ganancia minima luego de su calculo if(i == 0) { gananciaMinima = gananciaArticulos[i]; } else { if(gananciaArticulos[i] < gananciaMinima) { gananciaMinima = gananciaArticulos[i]; } } //Impresion en pantalla del calculo de ganancia realizado printf("Articulo: %s Precio Unitario: %.2f Ganancia: %.2f\n", nombreArticulos[i], precioUnitarioArticulos[i], gananciaArticulos[i]); } promedioGanancia = acumuladorGanancia / ARTICULOS; printf("=============================================================\n"); } bandera = 2; break; case 'c': if(bandera == 0) { printf("Cargue los registros de los articulos primero.\n"); } else { if(bandera == 1) { printf("Liste y calcule la ganancia de los articulos primero.\n"); } else { contadorGananciaMinima = 0; printf("=============== ARTICULOS CON MENOR GANANCIA ================\n"); for (int i = 0; i < ARTICULOS; i++) { if(gananciaArticulos[i] == gananciaMinima) { printf("Articulo: %s Precio Unitario: %.2f Ganancia: %.2f\n", nombreArticulos[i], precioUnitarioArticulos[i], gananciaArticulos[i]); contadorGananciaMinima++; } } printf("=============================================================\n"); printf("Se encontraron %i Articulo/s con ganancia minima\n", contadorGananciaMinima); } } break; case 'd': if(bandera == 0) { printf("Cargue los registros de los articulos primero.\n"); } else { if(bandera == 1) { printf("Liste y calcule la ganancia de los articulos primero.\n"); } else { printf("======= ARTICULOS QUE SUPERAN EL PROMEDIO DE GANANCIA =======\n"); for (int i = 0; i < ARTICULOS; i++) { if(gananciaArticulos[i] > promedioGanancia) { printf("Articulo: %s Precio Unitario: %.2f Ganancia: %.2f\n", nombreArticulos[i], precioUnitarioArticulos[i], gananciaArticulos[i]); } } printf("=============================================================\n"); printf("PROMEDIO DE GANANCIA: %.2f\n", promedioGanancia); } } break; } if(tolower(opcion) != SALIDA) { __fpurge(stdin); printf("Presione Enter para continuar..."); getchar(); } } while (tolower(opcion) != SALIDA); }
C
#include "Airport_Manager.h" // CODING THIS IN A T-BELL YEEEEEEAAAAAHHHHH /* - = - = - = - = - = - = - = - = - = - = - = - typedef struct Airport{ char * name; The airport name int numDestinations; The number of destinations the airport offers flights to struct Airport ** destinations; The array of destinations the airport offers flights to }Airport; - = - = - = - = - = - = - = - = - = - = - = - */ //Airport ** airports; /*The array of all airports managed by the company*/ //int numAirports; /*The current number of airports managed by the company*/ //int maxAirports; /*The max number of airports the airports array can store*/ // init global variables void createAirportArray() { airports = (Airport**)malloc(20 * sizeof(Airport*)); maxAirports = 20; numAirports = 0; } // add airport to globs int addAirport(Airport * airport) { // null check if (airport == NULL) return -1; // check if already exists int i; for (i = 0; i < maxAirports; i++) { if (airports[i] == airport) return 0; } // increase airports count numAirports++; // put in WERKKK if (numAirports == maxAirports) { maxAirports = maxAirports * 2; Airport ** newPorts = (Airport**)malloc(maxAirports * sizeof(Airport*)); int j; for (j = 0; j < numAirports-1; j++) { newPorts[j] = airports[j]; } free(airports); airports = newPorts; } // add it dood airports[numAirports-1] = airport; // 0 for already exists // 1 for added // -1 for invalid return 1; } // create dat airport, yo Airport * createAirport(const char * name) { // null check if (name == NULL) return NULL; Airport * portToReturn = malloc(sizeof(Airport)); char * nameDupe = strdup(name); portToReturn->name = nameDupe; portToReturn->numDestinations = 0; portToReturn->destinations = NULL; return portToReturn; } int addDestination(Airport * airport, Airport * dest) { // null check if (airport == NULL || dest == NULL) return -1; // check if first time int firstTime = 0; if (airport->destinations == NULL) { airport->destinations = (Airport**)malloc(sizeof(Airport*)); firstTime = 1; } // check if already added if (firstTime == 0) { int i; for (i = 0; i < airport->numDestinations; i++) { if (airport->destinations[i] == dest) return 0; } } // adddddddd it! if (firstTime == 1) { airport->destinations[0] = dest; } else if (firstTime == 0) { Airport ** toDest = (Airport**)malloc(airport->numDestinations+1 * sizeof(Airport*)); int i; for (i = 0; i < airport->numDestinations; i++) { toDest[i] = airport->destinations[i]; } free(airport->destinations); airport->destinations = toDest; airport->destinations[airport->numDestinations] = dest; } // increaes numDest airport->numDestinations++; // 0 for already exists // 1 for added // -1 for invalid return 1; } void printAirports() { printf("NumberOfAirports: %d\n", numAirports); int i; for (i = 0; i < numAirports; i++) { Airport * workingPort = airports[i]; printf("%s\n", workingPort->name); } printf("\n"); } int hasOneStopFlight(Airport * start, Airport * dest) { // null check if (start == NULL || dest == NULL) return -1; int i; for (i = 0; i < start->numDestinations; i++) { if (start->destinations[i] == dest) return 1; } return 0; } int hasTwoStopFlight(Airport * start, Airport * dest) { // null check if (start == NULL || dest == NULL) return -1; // check onestop first if (hasOneStopFlight(start, dest)) return 2; int i; for (i = 0; i < start->numDestinations; i++) { if (hasOneStopFlight(start->destinations[i], dest) == 1) return 1; } return 0; } void freeAllAirports() { int i; for (i = 0; i < numAirports; i++) { free(airports[i]->name); free(airports[i]->destinations); free(airports[i]); } } int main() { createAirportArray(); Airport * LAX = createAirport("LAX"); addAirport(LAX); Airport * MID = createAirport("MID"); addAirport(MID); Airport * EWR = createAirport("EWR"); addAirport(EWR); Airport * DANK = createAirport("DANK"); addAirport(DANK); int a; for (a = 0; a < 25; a++) { Airport * toAdd = createAirport("TEST"); addAirport(toAdd); } printAirports(); addDestination(LAX, MID); addDestination(MID, EWR); // COMMENT OUT FOR TWO FLIGHT TEST //addDestination(LAX, EWR); addDestination(LAX, DANK); printf("%d\n", hasTwoStopFlight(LAX, EWR)); freeAllAirports(); return 0; }
C
#include<stdio.h> int main() { int n; scanf("%d", &n); int val, avg=0, sum=0; int i=1; for(i=1; i<=n; i++){ scanf("%d", &val); sum = sum + val; } avg = sum / n; printf("%d", avg); return 0; }
C
#include "stm32f4xx.h" // Device header int main () { GPIO_InitTypeDef GPIO_InitStructure; /* RCC Configurations */ RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE); RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); /* TIM3 Configurations */ TIM_DeInit(TIM3); TIM_CounterModeConfig(TIM3, TIM_CounterMode_Up); TIM_PrescalerConfig(TIM3, 41999, TIM_PSCReloadMode_Update); TIM_SetAutoreload(TIM3, 1999); /* GPIOD Configurations for LEDs */ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_Init(GPIOD, &GPIO_InitStructure); GPIO_ResetBits(GPIOD, GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15); TIM_Cmd(TIM3, ENABLE); while (1) { if(TIM_GetCounter(TIM3)>0 && TIM_GetCounter(TIM3)<500) { GPIO_SetBits(GPIOD, GPIO_Pin_12); GPIO_ResetBits(GPIOD, GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15); } else if(TIM_GetCounter(TIM3)>=500 && TIM_GetCounter(TIM3)<1000) { GPIO_SetBits(GPIOD, GPIO_Pin_13); GPIO_ResetBits(GPIOD, GPIO_Pin_12 | GPIO_Pin_14 | GPIO_Pin_15); } else if(TIM_GetCounter(TIM3)>=1000 && TIM_GetCounter(TIM3)<1500) { GPIO_SetBits(GPIOD, GPIO_Pin_14); GPIO_ResetBits(GPIOD, GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_15); } else if(TIM_GetCounter(TIM3)>=1500 && TIM_GetCounter(TIM3)<2000) { GPIO_SetBits(GPIOD, GPIO_Pin_15); GPIO_ResetBits(GPIOD, GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_14); } } }
C
/* Hello World program */ #include<stdio.h> unsigned int get_digit(unsigned int value, unsigned int position); unsigned int count(unsigned int i); main() { unsigned int value; unsigned int position; position = 3; value = 231456; int digit; digit = get_digit(value, position); printf("%d", digit); } unsigned int get_digit(unsigned int value, unsigned int position) { if(count(value) < position){ return -1; } unsigned int digit = 0; for (int i = 0; i <= position; i++) { digit = value % 10; value = value / 10; } return digit; } unsigned int count(unsigned int i){ unsigned int number = 1; while(i/=10){ number++; } return number; }
C
/** * Author: Ritik Jain, 18114068 * Since: May 18, 2021 * Brief: Defines The Data and Lookahead buffers for text processing units. */ #include "stdio.h" #include "string.h" const int BUFFER_SIZE = 4; char DATA_BUFFER[4]; char LOOKAHEAD_BUFFER[4]; int DATA_PTR = 0; int LOOKAHEAD_PTR = 0; fpos_t LOOKAHEAD_INITIAL_POSITION; int LOOKAHEAD_USED = 0; int DATA_SIZE = 0; int LOOKAHEAD_SIZE = 0; int STREAM_CLOSED = 0; FILE *INPUT_FILE = NULL; void error(const char *msg) { printf("Error: "); printf(msg); printf("!\n"); } void raw_input_open(const char *filename) { INPUT_FILE = fopen(filename,"r"); if(INPUT_FILE == NULL) { STREAM_CLOSED = 1; error(strcat("Unable to open the file",filename)); } STREAM_CLOSED = 0; } void raw_input_close() { if(STREAM_CLOSED) return; STREAM_CLOSED = 1; fclose(INPUT_FILE); } int raw_is_readable() { if(STREAM_CLOSED || feof(INPUT_FILE)) return 0; return 1; } char raw_readchar() { if(!raw_is_readable()) return 0; return fgetc(INPUT_FILE); } int raw_read(char *dst, int max_len){ if(!raw_is_readable()) return 0; return fread(dst,sizeof(char),max_len,INPUT_FILE); } void load_lookahead_buffer() { LOOKAHEAD_PTR = 0; if(!LOOKAHEAD_USED){ LOOKAHEAD_USED = 1; if(!STREAM_CLOSED) fgetpos(INPUT_FILE,&LOOKAHEAD_INITIAL_POSITION); } LOOKAHEAD_SIZE = raw_read(LOOKAHEAD_BUFFER,BUFFER_SIZE); } void reset_lookahead_buffer(){ if(STREAM_CLOSED) return; fsetpos(INPUT_FILE,&LOOKAHEAD_INITIAL_POSITION); load_lookahead_buffer(); } void load_data_buffer() { if(!LOOKAHEAD_USED) load_lookahead_buffer(); else reset_lookahead_buffer(); memcpy(DATA_BUFFER,LOOKAHEAD_BUFFER,LOOKAHEAD_SIZE*sizeof(char)); DATA_PTR = 0; DATA_SIZE = LOOKAHEAD_SIZE; LOOKAHEAD_USED = 0; load_lookahead_buffer(); } int data_buffer_empty(){ return DATA_PTR == DATA_SIZE; } int data_buffer_full(){ return DATA_SIZE == BUFFER_SIZE; } int lookahead_buffer_empty(){ return LOOKAHEAD_PTR == LOOKAHEAD_SIZE; } int lookahead_buffer_full(){ return LOOKAHEAD_SIZE == BUFFER_SIZE; } int has_more_data(){ if(data_buffer_empty()) load_data_buffer(); if(data_buffer_empty()){ raw_input_close(); return 0; } return 1; } int has_more_lookahead(){ if(lookahead_buffer_empty()) load_lookahead_buffer(); if(lookahead_buffer_empty()) return 0; return 1; } char pop_chr(){ if(!has_more_data()) return 0; return DATA_BUFFER[DATA_PTR++]; } char peek_chr(){ if(!has_more_lookahead()) return 0; return LOOKAHEAD_BUFFER[LOOKAHEAD_PTR++]; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "linkedlist.h" // print current node void print_node (struct node *list) { printf("| %s: %s ", list->artist, list->name); printf("\n"); } // print the entire list void print_list (struct node *list) { while (list) { print_node(list); list = list->next; } } // find and return a pointer to the first song of an artist based on artist name struct node * find_artist(struct node *list, char *art) { printf("looking for [%s]\n", art); while (list) { if (strcmp(list->artist, art) == 0) { printf("artist found\n"); return list; } list = list->next; } printf("artist not found\n"); return NULL; } // find and return a pointer to a node based on artist and song name struct node * find_song(struct node *list, char *song, char *art) { printf("looking for [%s: %s]\n", art, song); while (list) { if (strcmp(list->artist, art) == 0 && strcmp(list->name, song) == 0) { printf("song found\n"); return list; } list = list->next; } printf("song not found\n"); return NULL; } // return the length of the list int get_length (struct node *list) { int length = 0; while (list) { list = list->next; length++; } return length; } // return a pointer to random element in the list struct node * get_random (struct node *list) { if (list) { int len = get_length(list); int num = rand() % len; while (num) { list = list->next; num--; } return list; } return NULL; } // insert node at the front struct node * insert_front (struct node *list, char *song, char *art) { struct node *new = malloc(sizeof(struct node)); strcpy(new->name, song); strcpy(new->artist, art); new->next = list; return new; } // insert nodes in order (alphabetical by Artist then by Song) struct node * insert_order (struct node *list, char *song, char *art) { if (list) { struct node *new = malloc(sizeof(struct node)); strcpy(new->name, song); strcpy(new->artist, art); if (list->next) { struct node *head = list; struct node *next = list->next; if (strcmp(head->artist, art) == 0 && strcmp(head->name, song) > 0) return insert_front(list, song, art); while (strcmp(next->artist, art) < 0) { head = head->next; next = head->next; } if (strcmp(next->artist, art) > 0) { next = insert_front(next, song, art); head->next = next; return list; } else if (strcmp(next->artist, art) == 0) { while (next && strcmp(next->artist, art) == 0 && strcmp(next->name, song) < 0) { head = head->next; next = head->next; } next = insert_front(next, song, art); head->next = next; return list; } } list->next = new; return list; } return insert_front(list, song, art); } // remove a single specified node from the list struct node * remove_node (struct node *list, char *song, char *art) { printf("removing [%s: %s]\n", art, song); struct node *head = list; if (list && strcmp(list->artist, art) == 0 && strcmp(list->name, song) == 0) { list = list->next; free(head); return list; } struct node *prev= list; struct node *temp= list; while (temp) { if (strcmp(temp->artist, art) == 0 && strcmp(temp->name, song) == 0) { if (temp) { if (!temp->next) { prev->next = NULL; free(temp); temp = NULL; } prev->next = temp->next; return list; } } prev = temp; temp = temp->next; } printf("[%s: %s] not found\n", art, song); return list; } // free the entire list struct node * free_list (struct node *list) { struct node *next; while (list) { printf("freeing node: %s - %s \n", list->artist, list->name); next = list->next; free(list); list = next; } printf("list after free_list:\n"); return NULL; }
C
// Author: Derek Gorthy // SID: 102359021 // References: Jack Dinkel, Luke Meszar, Sean Harris // // Description: This solution determines which page was least recently used and swaps it out for the next // page that is needed. /* * File: pager-predict.c * Author: Andy Sayler * http://www.andysayler.com * Adopted From: Dr. Alva Couch * http://www.cs.tufts.edu/~couch/ * * Project: CSCI 3753 Programming Assignment 4 * Create Date: Unknown * Modify Date: 2012/04/03 * Description: * This file contains a predictive pageit * implmentation. */ #include <stdio.h> #include <stdlib.h> #include "simulator.h" void pageit(Pentry q[MAXPROCESSES]) { /* Static vars */ static int initialized = 0; static int tick = 1; // artificial time static int timestamps[MAXPROCESSES][MAXPROCPAGES]; /* Local vars */ int proctmp; int pagetmp; int pc; int page; int proc; int jmin; int cur_lru; /* initialize static vars on first run */ if(!initialized){ for(proctmp=0; proctmp < MAXPROCESSES; proctmp++){ for(pagetmp=0; pagetmp < MAXPROCPAGES; pagetmp++){ timestamps[proctmp][pagetmp] = 0; } } initialized = 1; } // Must loop through all processes to make sure that every single page that is in is checked for(proc=0; proc<MAXPROCESSES; proc++) { // Determine if the process is active if(q[proc].active) { pc = q[proc].pc; // determine program counter page = pc/PAGESIZE; // page the program counter needs // Update when page was last used timestamps[proc][page] = tick; if(!q[proc].pages[page]) { // Attempt to swap page in, will enter if statement if all page slots are filled if(!pagein(proc,page)) { // Determine which page was used least recently cur_lru = -1; // Initialize the current LRU to -1 (will always change) for(pagetmp=0; pagetmp < MAXPROCPAGES; pagetmp++){ // Will be true if page is in and the timestamp shows it was used least recently if((tick - timestamps[proc][pagetmp]) > cur_lru && q[proc].pages[pagetmp]) { // Save the temp page jmin = pagetmp; cur_lru = (tick - timestamps[proc][pagetmp]); } } pageout(proc,jmin); } } } tick++; } }
C
/* * MIT License * * Copyright (c) 2020 Sebastian Zander * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef UTIL_H_ #define UTIL_H_ #include <stdlib.h> #include <string.h> #include <stdint.h> #include <assert.h> // arr_free // arr_size // arr_push // arr_pop // arr_clear // arr_resize // arr_reserve // usage: // int *test = NULL; // arr_push(test, 0); // arr_push(test, 1); // for(int i = 0; i < arr_size(test); ++i) // { // printf("%d ", test[i]; // } // arr_free(test); // test now set to NULL. #define ARR_MAGIC_ 0xFEFE0403 typedef struct { uint64_t magic; // magic is used to make sure we are not making a mistake int e, r, s; // element_size, reserve, size } arr_struct_; #define default_arr_size 10 #define arr_meta_(a) (((arr_struct_ *)(a)) - 1) #define assert_magic(a) (assert(a == NULL || arr_meta_(a)->magic == ARR_MAGIC_)) void *arr_init_(void **a, int elem_size); void *arr_realloc_(void **a, int ns); #define arr_init(a) ((!(a)) ? (arr_init_((void **)(&(a)), sizeof((a)[0]))) : (a)) // This is quite dumb. We malloc and then realloc // if we reserve a NULL array. Oh welp. We can // fix that later. #define arr_reserve(a, ns) do {\ assert_magic(a);\ if (!(a))\ arr_init_((void **)(&(a)), sizeof((a)[0]));\ if ((arr_meta_(a))->r < (ns))\ arr_realloc_((void **)(&(a)), ((ns) * 2 + default_arr_size));\ assert((arr_meta_(a))->r >= (ns));\ assert_magic(a);\ } while(0) #define arr_resize(a, ns) do {\ assert_magic(a);\ arr_reserve((a), ns);\ arr_meta_(a)->s = ns;\ assert_magic(a);\ } while(0) #define arr_size(a) ((a) ? arr_meta_(a)->s : 0) #define arr_push(a, v) do { \ assert_magic((a));\ arr_resize((a), (arr_size(a) + 1));\ (a)[((arr_size(a)) - 1)] = (v);\ assert_magic(a);\ } while(0) #define arr_insert(a, v, i) do { \ assert((i) >= 0);\ assert_magic(a);\ if (!a)\ {\ arr_push((a), v);\ }\ else \ {\ int size = arr_size(a);\ assert(i >= 0 && i < size + 1);\ arr_resize((a), size + 1);\ int elem_size = arr_meta_(a)->e;\ memmove(((char *)(a)) + ((i) + 1) * elem_size, \ ((char *)(a)) + (i) * elem_size, \ (size - (i)) * elem_size); \ (a)[i] = (v);\ }\ assert_magic(a);\ } while(0) #define arr_remove(a, i) do { \ assert(i >= 0);\ assert_magic(a);\ void *p = a;\ if (p)\ {\ int size = arr_size(a) - 1;\ assert((i) >= 0 && (i) < size + 1);\ int elem_size = arr_meta_(a)->e;\ memmove((char *)p + (i) * elem_size, \ (char *)p + ((i) + 1) * elem_size, \ (size - (i)) * elem_size); \ arr_resize((a), size);\ }\ assert_magic(a);\ } while(0) #define arr_pop(a) ((arr_meta_(a)->s = arr_size(a) - 1)) #define arr_first(a) ((a)[0]) #define arr_last(a) ((a)[arr_size(a) - 1]) #define arr_free(a) ((a) ? ((free(arr_meta_(a))), ((a) = NULL)) : NULL) #define arr_clear(a) arr_resize((a), 0) #define arr_begin(a) (a) #define arr_end(a) ((a) + arr_size(a)) // This works as .NETs Array.BinarySearch // Let i be the return value. // if i < 0 // the the value was not found. // Inserting the value into ~i of src // will result in src being sorted provided // it was sorted before. Note that it may be true // that (i == length of src). // otherwise i is the index in src of the value. // // The parameters are identical to those to bsearch static inline int arr_binarysearch(void *key, void *base, size_t num, size_t size, int (*compar) (const void* a, const void *b)) { int l = 0, r = num - 1; while (l <= r) { int m = (l + r) / 2; int cmp = compar((char *)base + (m * size), key); if (cmp < 0) { l = m + 1; } else if (cmp > 0) { r = m - 1; } else { return m; } } return ~l; } void arr_test(); #endif
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_split.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hmeriann <hmeriann@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/05/12 17:19:20 by hmeriann #+# #+# */ /* Updated: 2021/05/12 21:44:14 by hmeriann ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static char **array_free(char **res_array) { size_t i; i = 0; while (res_array[i]) { free(res_array[i]); res_array[i] = NULL; i++; } free(res_array); res_array = NULL; return (NULL); } static size_t words_counter(const char *s, size_t l, char c) { size_t words_count; int state; words_count = 0; state = 0; while (s[l] != '\0') { if (s[l] == c) state = 0; else if (state == 0) { state = 1; words_count++; } l++; } return (words_count); } static void action_with_str(const char *s, char **res_array, char c, \ size_t right) { size_t left; size_t line_num; line_num = 0; left = 0; while (s[right] != '\0') { while (s[right] == c && s[right] != '\0') right++; while (s[right] != c && s[right] != '\0') { right++; left++; } if (left > 0) { res_array[line_num] = ft_substr(s, right - left, left); if (res_array[line_num] == NULL) array_free(res_array); line_num++; left = 0; } } res_array[line_num] = NULL; } char **ft_split(char const *s, char c) { size_t right; size_t left; size_t words_count; char **res_array; if (s == NULL) return (NULL); left = 0; words_count = words_counter(s, left, c); res_array = (char **)malloc((words_count + 1) * sizeof(char *)); if (res_array == NULL) return (NULL); right = 0; action_with_str(s, res_array, c, right); return (res_array); }
C
/*--------------------------------------------------------------------------*/ /* */ /* HW08_141044086_Vakhid_Betrakhmadov */ /* */ /* main.c */ /* --------- */ /* Created on 04/22/2016 by Vakhid_Betrakhmadov */ /* */ /*--------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------*/ /* Includes */ /*--------------------------------------------------------------------------*/ #include <stdio.h> #include <math.h> #include <ctype.h> /*--------------------------------------------------------------------------*/ /* #defines */ /*--------------------------------------------------------------------------*/ #define BOARD_SIZE 8 /*---------------------------------------------------------------------------*/ /* Function Prototypes */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /* */ /* int isPieceMovable(char *board) */ /* ----------- */ /* */ /* board - chess board ( array of size 64 ) */ /* */ /* Return */ /* ------ */ /* 1 on success */ /* 0 on failer */ /* */ /* Description */ /* ----------- */ /* This function checks if the move is possiable according to the */ /* game's rules ( is piece movable itself, is target cell occupied by */ /* firendly piece */ /*---------------------------------------------------------------------------*/ int isPieceMovable(char *board, char sc, int sr, char tc, int tr); /*---------------------------------------------------------------------------*/ /* */ /* int isInCheck(char* board) */ /* ----------- */ /* */ /* board - chess board ( array of size 64 ) */ /* */ /* Returns */ /* ------ */ /* 1- if white king is in check */ /* 2- black king is in check */ /* 0- there is no check at all */ /* */ /* Description */ /* ----------- */ /* This function looks if either of kings on the board is currently in check */ /* This function returns it's result according to the last black and white */ /* kings found on the board,so there can be only one white and only one black*/ /* king on the board simultaneously for the correct result of the function */ /*---------------------------------------------------------------------------*/ int isInCheck(char* board); /*---------------------------------------------------------------------------*/ /* */ /* int makeMove(char *board, char sc, int sr, char tc, int tr) */ /* ----------- */ /* */ /* board - chess board ( array of size 64 ) */ /* sc- column of the source cell */ /* sr - row of the source cell */ /* tc- column of the target cell */ /* tr - row of the target cell */ /* */ /* Returns */ /* ------ */ /* 0 - move is invalid */ /* 1 - move is invalid because same player's king is in check */ /* 2 - move is valid */ /* 3 - move is valid and opponent player's king is in check */ /* */ /* Description */ /* ----------- */ /* This function makes move if the attempted move is possible according to */ /* the game's rules */ /*---------------------------------------------------------------------------*/ int makeMove(char *board, char sc, int sr, char tc, int tr); /*---------------------------------------------------------------------------*/ /* */ /* void initBoard(char *board) */ /* ----------- */ /* */ /* board - character array to store the chess board */ /* */ /* Return */ /* ------ */ /* Function does not return anything */ /* */ /* Description */ /* ----------- */ /* This function initializes the chess board by at first setting all */ /*elements of the array to spaces,and then placing the pieces in the correct */ /* order for both users */ /*---------------------------------------------------------------------------*/ void initBoard(char *board); /*---------------------------------------------------------------------------*/ /* */ /* void getPosition(char* col,int* row) */ /* ----------- */ /* */ /* col- column on the chess board */ /* row - row on the chess board */ /* */ /* Return */ /* ------ */ /* Function does not return anything */ /* */ /* Description */ /* ----------- */ /* This function gets to inputs from the user and return them through the */ /* pointers */ /*---------------------------------------------------------------------------*/ void getPosition(char* col,int* row); /*---------------------------------------------------------------------------*/ /* */ /* int isValidCell (char col,int row) */ /* ----------- */ /* */ /* col- column on the chess board */ /* row - row on the chess board */ /* */ /* Return */ /* ------ */ /* 1 on success */ /* 0 on failer */ /* */ /* Description */ /* ----------- */ /* This function checks whether given adress is within board's size */ /*---------------------------------------------------------------------------*/ int isValidCell (char col,int row); /*---------------------------------------------------------------------------*/ /* */ /* void printBoard (char *board) */ /* ----------- */ /* */ /* board - chess board ( array of size 64 ) */ /* */ /* Return */ /* ------ */ /* Function does not return anything */ /* */ /* Description */ /* ----------- */ /* This function prints the current state of the chess board on the screen */ /*---------------------------------------------------------------------------*/ void printBoard (char *board); /*---------------------------------------------------------------------------*/ /* */ /* int isKingMovable(char *board,char sourceCol, */ /* int sourceRow,char targetCol,int targetRow) */ /* ----------- */ /* */ /* board - chess board ( array of size 64 ) */ /* sourceCol- column of the source cell */ /* sourceRow - row of the source cell */ /* targetCol- column of the target cell */ /* targetRow - row of the target cell */ /* */ /* Return */ /* ------ */ /* 1 on success */ /* 0 on failer */ /* */ /* Description */ /* ----------- */ /* This function checks if a King is movable according to the game's rules */ /*---------------------------------------------------------------------------*/ int isKingMovable(char *board,char sourceCol,int sourceRow,char targetCol, int targetRow); /*---------------------------------------------------------------------------*/ /* */ /* int isRookMovable(char *board,char sourceCol,int sourceRow, */ /* char targetCol,int targetRow) */ /* ----------- */ /* */ /* board - chess board ( array of size 64 ) */ /* sourceCol- column of the source cell */ /* sourceRow - row of the source cell */ /* targetCol- column of the target cell */ /* targetRow - row of the target cell */ /* */ /* Return */ /* ------ */ /* 1 on success */ /* 0 on failer */ /* */ /* Description */ /* ----------- */ /* This function checks if a Rook is movable according to the game's rules */ /*---------------------------------------------------------------------------*/ int isRookMovable(char *board,char sourceCol,int sourceRow,char targetCol, int targetRow); /*---------------------------------------------------------------------------*/ /* */ /* int isBishopMovable(char *board,char sourceCol,int sourceRow, */ /* char targetCol,int targetRow) */ /* */ /* board - chess board ( array of size 64 ) */ /* sourceCol- column of the source cell */ /* sourceRow - row of the source cell */ /* targetCol- column of the target cell */ /* targetRow - row of the target cell */ /* */ /* Return */ /* ------ */ /* 1 on success */ /* 0 on failer */ /* */ /* Description */ /* ----------- */ /* This function checks if a Bishop is movable according to the game's rules */ /*---------------------------------------------------------------------------*/ int isBishopMovable(char *board,char sourceCol,int sourceRow,char targetCol, int targetRow); /*---------------------------------------------------------------------------*/ /* */ /* int isQueenMovable(char *board,char sourceCol,int sourceRow, */ /* char targetCol,int targetRow) */ /* */ /* board - chess board ( array of size 64 ) */ /* sourceCol- column of the source cell */ /* sourceRow - row of the source cell */ /* targetCol- column of the target cell */ /* targetRow - row of the target cell */ /* */ /* Return */ /* ------ */ /* 1 on success */ /* 0 on failer */ /* */ /* Description */ /* ----------- */ /* This function checks if a Queen is movable according to the game's rules */ /*---------------------------------------------------------------------------*/ int isQueenMovable(char *board,char sourceCol,int sourceRow,char targetCol, int targetRow); /*---------------------------------------------------------------------------*/ /* */ /* int isKnightMovable(char *board,char sourceCol,int sourceRow, */ /* char targetCol,int targetRow) */ /* */ /* board - chess board ( array of size 64 ) */ /* sourceCol- column of the source cell */ /* sourceRow - row of the source cell */ /* targetCol- column of the target cell */ /* targetRow - row of the target cell */ /* */ /* Return */ /* ------ */ /* 1 on success */ /* 0 on failer */ /* */ /* Description */ /* ----------- */ /* This function checks if a Knight is movable according to the game's rules */ /*---------------------------------------------------------------------------*/ int isKnightMovable(char *board,char sourceCol,int sourceRow,char targetCol, int targetRow); /*---------------------------------------------------------------------------*/ /* */ /* int isPawnMovable(char *board,char sourceCol, */ /* int sourceRow,char targetCol,int targetRow) */ /* */ /* board - chess board ( array of size 64 ) */ /* sourceCol- column of the source cell */ /* sourceRow - row of the source cell */ /* targetCol- column of the target cell */ /* targetRow - row of the target cell */ /* */ /* Return */ /* ------ */ /* 1 on success */ /* 0 on failer */ /* */ /* Description */ /* ----------- */ /* This function checks if a Pawn is movable according to the game's rules */ /*---------------------------------------------------------------------------*/ int isPawnMovable(char *board,char sourceCol,int sourceRow,char targetCol, int targetRow); /*---------------------------------------------------------------------------*/ /* */ /* char whatIsInTheCell(char *board,char col,int row */ /* */ /* board - chess board ( array of size 64 ) */ /* сol- column on the chess board */ /* row - number of row on the chess board */ /* */ /* Return */ /* ------ */ /* content of the cell with adress col and row */ /* */ /* Description */ /* ----------- */ /* This function figures out what is curently loccated in the cell */ /*---------------------------------------------------------------------------*/ char whatIsInTheCell(char *board,char col,int row); /*---------------------------------------------------------------------------*/ /* */ /* int adressOfTheCell(char col,int row ) */ /* */ /* сol- column on the chess board */ /* row - number of row on the chess board */ /* */ /* Return */ /* ------ */ /* Decimal adress in the array */ /* */ /* Description */ /* ----------- */ /* This function converts adress of the cell on the chess board given by */ /* column letter and row number to decimal adress in the array */ /*---------------------------------------------------------------------------*/ int adressOfTheCell(char col,int row); /*---------------------------------------------------------------------------*/ /* */ /* int getPlayer(char *board, char col,int row) */ /* */ /* board - chess board ( array of size 64 ) */ /* сol- column on the chess board */ /* row - number of row on the chess board */ /* */ /* Return */ /* ------ */ /* 1- the piece is white(upper case ) */ /* 0- the piece is black(lower case ) */ /* Description */ /* ----------- */ /* This function check's the collor of the piece in the cell with adress col */ /* and row on the board */ /*---------------------------------------------------------------------------*/ int getPlayer(char *board, char col,int row); /*---------------------------------------------------------------------------*/ /* */ /* int isBlack(int currPlayer) */ /* */ /* currPlayer-integer indicating current player (1 -white,0 -black) */ /* */ /* Return */ /* ------ */ /* 1- currPlayer==0 */ /* 0- currPlayer==1 */ /* Description */ /* ----------- */ /* This function is true if the currPlayer is black(0) */ /*---------------------------------------------------------------------------*/ int isBlack(int currPlayer); /*---------------------------------------------------------------------------*/ /* */ /* int isBlack(int currPlayer) */ /* */ /* currPlayer-integer indicating current player (1 -white,0 -black) */ /* */ /* Return */ /* ------ */ /* 1- currPlayer==1 */ /* 0- currPlayer==0 */ /* Description */ /* ----------- */ /* This function is true if the currPlayer is white(1) */ /*---------------------------------------------------------------------------*/ int isWhite(int currPlayer); /*---------------------------------------------------------------------------*/ /* */ /* void kingsLocation(char *board,char *whiteKingCol,int* whiteKingRow, */ /* char* blackKingCol,int* blackKingRow) */ /* */ /* board - chess board ( array of size 64 ) */ /* whiteKingCol - column of the white kings current location on the board */ /* whiteKingRow - row of the white kings current location on the board */ /* blackKingCol - column of the black kings current location on the board */ /* blackKingRow - row of the black kings current location on the board */ /* */ /* Return */ /* ------ */ /* Returns ,through the pointers mentioned above ,current loccations of the */ /* white and black king on the board */ /* */ /* Description */ /* ----------- */ /* This function finds and returns current loccations of the last white and */ /* black king found on the board */ /*---------------------------------------------------------------------------*/ void kingsLocation(char *board,char *whiteKingCol,int* whiteKingRow, char* blackKingCol,int* blackKingRow); /*---------------------------------------------------------------------------*/ /* */ /* void moveThePiece(char *board,char sourceCol,int sourceRow,char targetCol,*/ /* int targetRow) */ /* */ /* board - chess board ( array of size 64 ) */ /* sourceCol- column of the source cell */ /* sourceRow - row of the source cell */ /* targetCol- column of the target cell */ /* targetRow - row of the target cell */ /* */ /* Return */ /* ------ */ /* Nothing */ /* ----------- */ /* This function moves piece from source adress to the target adress filling */ /* source adress with empty character */ /*---------------------------------------------------------------------------*/ void moveThePiece(char *board,char sourceCol,int sourceRow,char targetCol, int targetRow); /******************************************************************************/ int main() { char board [BOARD_SIZE*BOARD_SIZE], empty; int player = 1; /* 1 white, 0 black */ char sc,tc; /* source/target cols */ int sr,tr; /* source/target rows */ int moveStatus = 0; int checkStatus = 0; char currPlayer; initBoard(board); do { printBoard(board); printf("%s player move > ", player ? "White" : "Black"); getPosition(&sc,&sr); scanf("%c", &empty); getPosition(&tc,&tr); scanf("%c", &empty); /*emptyBuffer();*/ currPlayer = getPlayer(board, sc,sr); if(!isValidCell(sc,sr)) { printf("Source position is invalid\n"); continue; } if(!isValidCell(tc,tr)) { printf("Target position is invalid\n"); continue; } if((isBlack(currPlayer) && player) || (isWhite(currPlayer) && !player)) { printf("Illegal piece. \n"); continue; } moveStatus = makeMove(board,sc,sr,tc,tr); switch(moveStatus) { case 0: printf("Invalid move!\n"); break; case 1: printf("Your king is in check!\n"); ++checkStatus; break; case 3: printf("Check!\n "); case 2: player = !player; checkStatus = 0; break; } } while(checkStatus < 2); printf("%s player WINS!\n", player ? "Black":"White" ); return 0; } /******************************************************************************/ /*---------------------------------------------------------------------------*/ /* Function Implementations */ /*---------------------------------------------------------------------------*/ /*here we have empty buffer function*/ void emptyBuffer(void) { char tresh; while(tresh!='\n') { scanf("%c",&tresh); } } /* Function getPlayer */ /* ----------- */ /* This function check's the collor of the piece in the cell with adress col */ /* and row on the board */ /*---------------------------------------------------------------------------*/ /*here we have function which looks what's in the source adress*/ /*Returns: >1 if white player is trying to make a move */ /* >2 if black player is trying to make a move */ int getPlayer(char *board, char col,int row) { if(isValidCell(col,row)) { if(isupper(whatIsInTheCell(board,col,row))) { return 1; } else { return 0; } } return 0 ; } /*---------------------------------------------------------------------------*/ /* Function isBlack */ /* ----------- */ /* This function is true if the currPlayer is black(0) */ /*---------------------------------------------------------------------------*/ int isBlack(int currPlayer) { if(!currPlayer) { return 1; } else { return 0; } } /*---------------------------------------------------------------------------*/ /* Function isWhite */ /* ----------- */ /* This function is true if the currPlayer is white(1) */ /*---------------------------------------------------------------------------*/ int isWhite(int currPlayer) { if(currPlayer) { return 1; } else { return 0; } } /*---------------------------------------------------------------------------*/ /* Function getPosition */ /* ----------- */ /* This function gets to inputs from the user and return them through the */ /* pointers */ /*---------------------------------------------------------------------------*/ void getPosition(char* col,int* row) { scanf("%c%d",col,row); } /* Function isValidCell */ /* ----------- */ /* This function checks whether given adress is within board's size */ /*---------------------------------------------------------------------------*/ /*here we check if the entered adress is within board size*/ int isValidCell (char col,int row) { if(((col>='a') && (col<='h')) && ((row>=1)&&(row<=8)) ) return 1; else return 0; } /* Function whatIsInTheCell */ /* ----------- */ /* This function figures out what is curently loccated in the cell */ /*---------------------------------------------------------------------------*/ /*here we return the piece loccated in the cell with adress col and row*/ char whatIsInTheCell(char *board,char col,int row) { int adress=0; /*if we start to check beyond the board (cases col<a or row>8*/ if (isValidCell(col,row)==0) { return ' '; } adress = adressOfTheCell(col,row); /*returns the content of the cell */ return board[adress]; } /* Function adressOfTheCell */ /* ----------- */ /* This function converts adress of the cell on the chess board given by */ /* column letter and row number to decimal adress in the array */ /*---------------------------------------------------------------------------*/ /*here we convert col-row adress on the board to the appropriate array index */ int adressOfTheCell(char col,int row) { int column; if(isValidCell(col,row)==0) { return 0; } switch (col) { case 'a':column=0;break; case 'b':column=1;break; case 'c':column=2;break; case 'd':column=3;break; case 'e':column=4;break; case 'f':column=5;break; case 'g':column=6;break; case 'h':column=7;break; default:break; } /*formule for the adress of the cell on the board (8*(8-row)+col)*/ return((8*(8-row))+(column)); } /* Function initBoard */ /* ----------- */ /* This function gets to inputs from the user and return them through the */ /* pointers */ /*---------------------------------------------------------------------------*/ /*here we initialize the board*/ void initBoard(char *board) { int i; for(i=0;i<64;++i) board[i]=' '; /*Black pieces on the board */ board[0]='r'; board[1]='n'; board[2]='b'; board[3]='q'; board[4]='k'; board[5]='b'; board[6]='n'; board[7]='r'; for (i=8;i<16;++i) { board[i]='p'; } /*White pieces on the board */ board[56]='R'; board[57]='N'; board[58]='B'; board[59]='Q'; board[60]='K'; board[61]='B'; board[62]='N'; board[63]='R'; for (i=48;i<56;++i) { board[i]='P'; } } /* Function printBoard */ /* ----------- */ /* This function prints the current state of the chess board on the screen */ /*---------------------------------------------------------------------------*/ void printBoard (char *board) { int i,j; printf (" a b c d e f g h\n"); printf(" - - - - - - - -\n"); /* prints bord ,line by line */ for(i=8;i!=0;--i) { /*ptints numbers on the left side of the board */ printf("%d|",i); for(j=(8*(8-i));j<8*(9-i);++j) { printf("%c",board[j]); /*leaves spaces between the characters on the board, omiting the space */ /* after last character of each line */ if(j!=(8*(9-i)-1)) printf(" "); } /*gets to the new line at the end of each line */ printf("|"); printf("\n"); } printf(" - - - - - - - -\n"); } /* Function kingsLocation */ /* ----------- */ /* This function finds and returns current loccations of the last white and */ /* black king found on the board */ /*---------------------------------------------------------------------------*/ /* Here we find current location of both kings on the board*/ /* Because the function returns positions of the last found pair of kings*/ /* (white and black) there can be only one black and only one white king */ /* simultaneously on the board*/ void kingsLocation(char *board,char *whiteKingCol,int* whiteKingRow, char* blackKingCol,int* blackKingRow) { int row; char col; for(row=1;row<=BOARD_SIZE;++row) { for(col='a';col<='h';++col) { if(whatIsInTheCell(board,col,row)=='K') { *whiteKingCol=col; *whiteKingRow=row; } else if(whatIsInTheCell(board,col,row)=='k') { *blackKingCol=col; *blackKingRow=row; } else { /*do nothing*/ } } } } /* Function moveThePiece */ /* ----------- */ /* This function moves piece from source adress to the target adress filling */ /* source adress with empty character */ /*---------------------------------------------------------------------------*/ /*here we move piece on the board from source adress to the target adress*/ void moveThePiece(char *board,char sourceCol,int sourceRow,char targetCol, int targetRow) { int sourceAdress; int targetAdress; sourceAdress=adressOfTheCell(sourceCol, sourceRow); targetAdress=adressOfTheCell(targetCol, targetRow); board[targetAdress]=board[sourceAdress]; board[sourceAdress]=' '; } /* Function makeMove */ /* ----------- */ /* This function makes move if the attempted move is possible according to */ /* the game's rules */ /*---------------------------------------------------------------------------*/ /*here we check if the move can be accomplished according to the game's rules*/ /*and move it if yes */ int makeMove(char *board, char sc, int sr, char tc, int tr) { int currPlayer; char tempPiece; /*here we figure out whose turn it is */ currPlayer = getPlayer(board, sc,sr); /*if piece is inmovable - move is invalid*/ if(isPieceMovable(board,sc,sr,tc,tr)==0) { return 0; } /*else if piece is movable*/ else { /*we look if the current player's king is in check*/ if((isInCheck(board)==1 && isWhite(currPlayer))|| (isInCheck(board)==2 && isBlack(currPlayer))) { /*if yes,we look if he is still in check after the attempted move*/ /*takes piece in target cell to the temp variable*/ tempPiece=whatIsInTheCell(board,tc,tr); /*makes move*/ moveThePiece(board,sc,sr,tc,tr); /*checks if the current player's king is in check again after the move*/ /*if yes - backs the move,returns 1 (so move is invalid)*/ if((isInCheck(board)==1 && isWhite(currPlayer))|| (isInCheck(board)==2 && isBlack(currPlayer))) { /*here we reverse the move*/ moveThePiece(board,tc,tr,sc,sr); board[adressOfTheCell(tc,tr)]=tempPiece; return 1; } /*the player's king is not in check anymore after the move */ /*so the move is valid,now let's see what's going on with */ /*opponent player's king */ /*opponent player's king is in check after the move*/ if((isInCheck(board)==1 && isBlack(currPlayer))|| (isInCheck(board)==2 && isWhite(currPlayer))) { return 3; } /*here we just rescued the king*/ return 2; } tempPiece=whatIsInTheCell(board,tc,tr); moveThePiece(board,sc,sr,tc,tr); /***********************************************/ /* IS THERE A CHECK FOR ME AFTER THE MOVE */ /**********************************************/ /*checks if current player's king is in check after the move*/ if((isInCheck(board)==1 && isWhite(currPlayer))|| (isInCheck(board)==2 && isBlack(currPlayer))) { /*here we reverse the move*/ moveThePiece(board,tc,tr,sc,sr); board[adressOfTheCell(tc,tr)]=tempPiece; return 1; } /*opponent player's king is in check after the move*/ if((isInCheck(board)==1 && isBlack(currPlayer))|| (isInCheck(board)==2 && isWhite(currPlayer))) { return 3; } return 2; } return 0; } /* Function isPieceMovable */ /* ----------- */ /* This function checks if the move is possiable according to the */ /* game's rules ( is piece movable itself, is target cell occupied by */ /* firendly piece */ /*---------------------------------------------------------------------------*/ /* here we check if the particular piece can move the required way and if */ /* the target cell is not occuppied by any friendly piece */ int isPieceMovable(char *board, char sc, int sr, char tc, int tr) { char sourceCage; char targetCage; /*checks what is in the source and target cells given by user */ sourceCage=whatIsInTheCell(board,sc,sr); targetCage=whatIsInTheCell(board,tc,tr); /*calls appropriate function according to the piece loccated in the source*/ /*cell*/ switch(sourceCage) { case 'p': { /*checks if the piece is movable according to the game's rules */ /*and if the target cell is occupied by a friendly piece */ if(isPawnMovable(board,sc,sr,tc,tr) && !(targetCage>='a' && targetCage<='z')) { return 1; } else { return 0; } }break; case 'P': { if(isPawnMovable(board,sc,sr,tc,tr) && !(targetCage>='A' && targetCage<='Z')) { return 1; } else { return 0; } }break; case 'r': { if(isRookMovable(board,sc,sr,tc,tr)&& !(targetCage>='a' && targetCage<='z')) { return 1; } else { return 0; } }break; case 'R': { if(isRookMovable(board,sc,sr,tc,tr)&& !(targetCage>='A' && targetCage<='Z')) { return 1; } else { return 0; } }break; case 'n': { if(isKnightMovable(board,sc,sr,tc,tr)&& !(targetCage>='a' && targetCage<='z')) { return 1; } else { return 0; } }break; case 'N': { if(!(targetCage>='A' && targetCage<='Z') && (isKnightMovable(board,sc,sr,tc,tr))) { return 1; } else { return 0; } }break; case 'b': { if(isBishopMovable(board,sc,sr,tc,tr)&& !(targetCage>='a' && targetCage<='z')) { return 1; } else { return 0; } }break; case 'B': { if(isBishopMovable(board,sc,sr,tc,tr)&& !(targetCage>='A' && targetCage<='Z')) { return 1; } else { return 0; } }break; case 'q': { if(isQueenMovable(board,sc,sr,tc,tr)&& !(targetCage>='a' && targetCage<='z')) { return 1; } else { return 0; } }break; case 'Q': { if(isQueenMovable(board,sc,sr,tc,tr)&& !(targetCage>='A' && targetCage<='Z')) { return 1; } else { return 0; } }break; case 'k': { if(isKingMovable(board,sc,sr,tc,tr)&& !(targetCage>='a' && targetCage<='z')) { return 1; } else { return 0; } }break; case 'K': { if(isKingMovable(board,sc,sr,tc,tr)&& !(targetCage>='A' && targetCage<='Z')) { return 1; } else { return 0; } }break; default: { return 0; }break; } return 0; } /* Function isInCheck */ /* ----------- */ /* This function looks if either of kings on the board is currently in check */ /* This function returns it's result according to the last black and white */ /* kings found on the board,so there can be only one white and only one black*/ /* king on the board simultaneously for the correct result of the function */ /*---------------------------------------------------------------------------*/ int isInCheck(char* board) { char whiteKingCol; int whiteKingRow; char blackKingCol; int blackKingRow; int i,j; int safe; char cellContent; /*finds the current location of the both kings on the board*/ kingsLocation(board,&whiteKingCol,&whiteKingRow,&blackKingCol, &blackKingRow); /*-----------------FOR THE WHITE KING------------------*/ /*checks if there is enemy pawn nearby*/ if(whatIsInTheCell(board,whiteKingCol+1,whiteKingRow+1)=='p' || whatIsInTheCell(board,whiteKingCol-1,whiteKingRow+1)=='p') { return 1; } /*checks if there is a knight nearby*/ if (whatIsInTheCell(board,whiteKingCol+1,whiteKingRow+2)=='n' || whatIsInTheCell(board,whiteKingCol+2,whiteKingRow+1)=='n' || whatIsInTheCell(board,whiteKingCol+1,whiteKingRow-2)=='n' || whatIsInTheCell(board,whiteKingCol+2,whiteKingRow-1)=='n' || whatIsInTheCell(board,whiteKingCol-1,whiteKingRow+2)=='n' || whatIsInTheCell(board,whiteKingCol-2,whiteKingRow+1)=='n' || whatIsInTheCell(board,whiteKingCol-1,whiteKingRow-2)=='n' || whatIsInTheCell(board,whiteKingCol-2,whiteKingRow-1)=='n') { return 1; } safe=0; /*scans for the check to the right of the row */ for(i=whiteKingCol+1;i<='h';++i) { cellContent=whatIsInTheCell(board,i,whiteKingRow); /*indicates that the pass is safe if there is a friendly piece on the row*/ if((cellContent>='A' && cellContent<='Z') || cellContent=='p' || cellContent=='n' || cellContent=='b' || cellContent=='k') { safe=1; } /*quits if there is queen or rook on the row and the pass is not safe */ if((cellContent=='q' || cellContent=='r') && safe==0) { return 1; } } safe=0; /*scans for the check to the left of the row */ for(i=whiteKingCol-1;i>='a';--i) { cellContent=whatIsInTheCell(board,i,whiteKingRow); /*indicates that the pass is safe if there is a friendly piece on the row*/ if((cellContent>='A' && cellContent<='Z') || cellContent=='p' || cellContent=='n' || cellContent=='b' || cellContent=='k') { safe=1; } /*quits if there is queen or rook on the row and the pass is not safe */ if((cellContent=='q' || cellContent=='r') && safe==0) { return 1; } } safe=0; /*scans the column up for the check */ for(i=whiteKingRow+1;i<=8;++i) { cellContent=whatIsInTheCell(board,whiteKingCol,i); /*indicates that the pass is safe if there is a friendly piece on the column*/ if((cellContent>='A' && cellContent<='Z') || cellContent=='p' || cellContent=='n' || cellContent=='b' || cellContent=='k') { safe=1; } /*quits if there is queen or rook on the column and the pass is not safe */ if((cellContent=='q' || cellContent=='r') && safe==0) { return 1; } } safe=0; /*scans the column down for the check*/ for(i=whiteKingRow-1;i>=1;--i) { cellContent=whatIsInTheCell(board,whiteKingCol,i); /*indicates that the pass is safe if there is a friendly piece on the clumn*/ if((cellContent>='A' && cellContent<='Z') || cellContent=='p' || cellContent=='n' || cellContent=='b' || cellContent=='k') { safe=1; } /*quits if there is queen or rook on the column and the pass is not safe */ if((cellContent=='q' || cellContent=='r') && safe==0) { return 1; } } safe=0; /*scans diagonally right up for the check*/ for(i=whiteKingCol+1,j=whiteKingRow+1;i<='h' && j<=8;++i,++j) { cellContent=whatIsInTheCell(board,i,j); /*indicates that the pass is safe if there is a friendly piece on the clumn*/ if((cellContent>='A' && cellContent<='Z' && cellContent!='K') || cellContent=='r' || cellContent=='n' || cellContent=='k' || cellContent=='p') { safe=1; } /*quits if there is queen or rook on the column and the pass is not safe */ if((cellContent=='b' || cellContent=='q') && safe==0) { return 1; } } safe=0; /*scans diagonally right down for the check */ for(i=whiteKingCol+1,j=whiteKingRow-1;i<='h' && j>=1;++i,--j) { cellContent=whatIsInTheCell(board,i,j); /*indicates that the pass is safe if there is a friendly piece on the clumn*/ if((cellContent>='A' && cellContent<='Z') || cellContent=='r' || cellContent=='n' || cellContent=='k' || cellContent=='p') { safe=1; } /*quits if there is queen or rook on the column and the pass is not safe */ if((cellContent=='b' || cellContent=='q') && safe==0) { return 1; } } safe=0; /*scans diagonally left up for the check */ for(i=whiteKingCol-1,j=whiteKingRow+1;i>='a' && j<=8;--i,++j) { cellContent=whatIsInTheCell(board,i,j); /*indicates that the pass is safe if there is a friendly piece on the clumn*/ if((cellContent>='A' && cellContent<='Z' && cellContent!='K') || cellContent=='r' || cellContent=='n' || cellContent=='k' || cellContent=='p') { safe=1; } /*quits if there is queen or rook on the column and the pass is not safe */ if((cellContent=='b' || cellContent=='q') && safe==0) { return 1; } } safe=0; /*scans diagonally left down for the check */ for(i=whiteKingCol-1,j=whiteKingRow-1;i>='a' && j>=1;--i,--j) { cellContent=whatIsInTheCell(board,i,j); /*indicates that the pass is safe if there is a friendly piece on the clumn*/ if((cellContent>='A' && cellContent<='Z') || cellContent=='r' || cellContent=='n' || cellContent=='k' || cellContent=='p') { safe=1; } /*quits if there is queen or rook on the column and the pass is not safe */ if((cellContent=='b' || cellContent=='q') && safe==0) { return 1; } } /*---------------------FOR THE BLACK KING---------------------- */ /*checks if there is enemy pawn nearby*/ if(whatIsInTheCell(board,blackKingCol+1,blackKingRow-1)=='P' || whatIsInTheCell(board,blackKingCol-1,blackKingRow-1)=='P') { return 2; } /*checks if there is a knight nearby*/ if (whatIsInTheCell(board,blackKingCol+1,blackKingRow+2)=='N' || whatIsInTheCell(board,blackKingCol+2,blackKingRow+1)=='N' || whatIsInTheCell(board,blackKingCol+1,blackKingRow-2)=='N' || whatIsInTheCell(board,blackKingCol+2,blackKingRow-1)=='N' || whatIsInTheCell(board,blackKingCol-1,blackKingRow+2)=='N' || whatIsInTheCell(board,blackKingCol-2,blackKingRow+1)=='N' || whatIsInTheCell(board,blackKingCol-1,blackKingRow-2)=='N' || whatIsInTheCell(board,blackKingCol-2,blackKingRow-1)=='N') { return 2; } safe=0; /*scans for the check to the right of the row */ for(i=blackKingCol+1;i<='h';++i) { cellContent=whatIsInTheCell(board,i,blackKingRow); /*indicates that the pass is safe if there is a friendly piece on the row*/ if((cellContent>='a' && cellContent<='z') || cellContent=='P' || cellContent=='N' || cellContent=='B' || cellContent=='K') { safe=1; } /*quits if there is queen or rook on the row and the pass is not safe */ if((cellContent=='Q' || cellContent=='R') && safe==0) { return 2; } } safe=0; /*scans for the check to the left of the row */ for(i=blackKingCol-1;i>='a';--i) { cellContent=whatIsInTheCell(board,i,blackKingRow); /*indicates that the pass is safe if there is a friendly piece on the row*/ if((cellContent>='a' && cellContent<='z') || cellContent=='P' || cellContent=='N' || cellContent=='B' || cellContent=='K') { safe=1; } /*quits if there is queen or rook on the row and the pass is not safe */ if((cellContent=='Q' || cellContent=='R') && safe==0) { return 2; } } safe=0; /*scans the column up for the check */ for(i=blackKingRow+1;i<=8;++i) { cellContent=whatIsInTheCell(board,blackKingCol,i); /*indicates that the pass is safe if there is a friendly piece on the clumn*/ if((cellContent>='a' && cellContent<='z') || cellContent=='P' || cellContent=='N' || cellContent=='B' || cellContent=='K') { safe=1; } /*quits if there is queen or rook on the column and the pass is not safe */ if((cellContent=='Q' || cellContent=='R') && safe==0) { return 2; } } safe=0; /*scans the column down for the check*/ for(i=blackKingRow-1;i>=1;--i) { cellContent=whatIsInTheCell(board,blackKingCol,i); /*indicates that the pass is safe if there is a friendly piece on the clumn*/ if((cellContent>='a' && cellContent<='z') || cellContent=='P' || cellContent=='N' || cellContent=='B' || cellContent=='K') { safe=1; } /*quits if there is queen or rook on the column and the pass is not safe */ if((cellContent=='Q' || cellContent=='R') && safe==0) { return 2; } } safe=0; /*scans diagonally right up for the check*/ for(i=blackKingCol+1,j=blackKingRow+1;i<='h' && j<=8;++i,++j) { cellContent=whatIsInTheCell(board,i,j); /*indicates that the pass is safe if there is a friendly piece on the clumn*/ if((cellContent>='a' && cellContent<='z' && cellContent!='k') || cellContent=='R' || cellContent=='N' || cellContent=='K' || cellContent=='P') { safe=1; } /*quits if there is queen or rook on the column and the pass is not safe */ if((cellContent=='B' || cellContent=='Q') && safe==0) { return 2; } } safe=0; /*scans diagonally right down for the check */ for(i=blackKingCol+1,j=blackKingRow-1;i<='h' && j>=1;++i,--j) { cellContent=whatIsInTheCell(board,i,j); /*indicates that the pass is safe if there is a friendly piece on the clumn*/ if((cellContent>='a' && cellContent<='z') || cellContent=='R' || cellContent=='N' || cellContent=='K' || cellContent=='P') { safe=1; } /*quits if there is queen or rook on the column and the pass is not safe*/ if((cellContent=='B' || cellContent=='Q') && safe==0) { return 2; } } safe=0; /*scans diagonally left up for the check */ for(i=blackKingCol-1,j=blackKingRow+1;i>='a' && j<=8;--i,++j) { cellContent=whatIsInTheCell(board,i,j); /*indicates that the pass is safe if there is a friendly piece on the clumn*/ if((cellContent>='a' && cellContent<='z' && cellContent!='k') || cellContent=='R' || cellContent=='N' || cellContent=='K' || cellContent=='P') { safe=1; } /*quits if there is queen or rook on the column and the pass is not safe */ if((cellContent=='B' || cellContent=='Q') && safe==0) { return 2; } } safe=0; /*scans diagonally left down for the check */ for(i=blackKingCol-1,j=blackKingRow-1;i>='a' && j>=1;--i,--j) { cellContent=whatIsInTheCell(board,i,j); /*indicates that the pass is safe if there is a friendly piece on the clumn*/ if((cellContent>='a' && cellContent<='z') || cellContent=='R' || cellContent=='N' || cellContent=='K' || cellContent=='P') { safe=1; } /*quits if there is queen or rook on the column and the pass is not safe */ if((cellContent=='B' || cellContent=='Q') && safe==0) { return 2; } } /*if no king is in check*/ return 0; } /* Function isKingMovable */ /* ----------- */ /* This function checks if a King is movable according to the game's rules */ /*---------------------------------------------------------------------------*/ int isKingMovable(char *board,char sourceCol,int sourceRow,char targetCol, int targetRow) { /*checks if the move is one step move in any direction */ if ((targetCol==sourceCol || targetCol==sourceCol+1 || targetCol==sourceCol-1) && (targetRow==sourceRow || targetRow==sourceRow+1 || targetRow==sourceRow-1)) { return 1; } else { return 0; } return 0; } /* Function isRookMovable */ /* ----------- */ /* This function checks if a Rook is movable according to the game's rules */ /*---------------------------------------------------------------------------*/ int isRookMovable(char *board,char sourceCol,int sourceRow,char targetCol, int targetRow) { /* column and row moves.The same as in the queen function */ int i; if(targetCol==sourceCol) { if(targetRow>sourceRow) { for(i=sourceRow+1;i<targetRow;++i) { if (whatIsInTheCell(board,sourceCol,i)!=' ') { return 0; } } return 1; } else { for(i=sourceRow-1;i>targetRow;--i) { if (whatIsInTheCell(board,sourceCol,i)!=' ') { return 0; } } return 1; } } else if (targetRow==sourceRow) { if(targetCol>sourceCol) { for(i=sourceCol+1;i<targetCol;++i) { if (whatIsInTheCell(board,i,sourceRow)!=' ') { return 0; } } return 1; } else { for(i=sourceCol-1;i>targetCol;--i) { if (whatIsInTheCell(board,i,sourceRow)!=' ') { return 0; } } return 1; } } else { return 0; } return 0; } /* Function isBishopMovable */ /* ----------- */ /* This function checks if a Bishop is movable according to the game's rules */ /*---------------------------------------------------------------------------*/ int isBishopMovable(char *board,char sourceCol,int sourceRow,char targetCol, int targetRow) { /*Diagonal moves . The same as in the queen function*/ int i,j; if((targetCol>sourceCol)&&(targetRow>sourceRow)) { j=sourceRow; for(i=sourceCol;i<targetCol;++i) { if ((whatIsInTheCell(board,i,j)!=' ') && (whatIsInTheCell(board,i,j)!=whatIsInTheCell(board,sourceCol, sourceRow))) { return 0; } ++j; } if ((targetCol-i==0)&&(targetRow-j==0)) return 1; else return 0; } else if ((targetCol>sourceCol)&&(targetRow<sourceRow)) { j=sourceRow; for(i=sourceCol;i<targetCol;++i) { if ((whatIsInTheCell(board,i,j)!=' ') && (whatIsInTheCell(board,i,j)!=whatIsInTheCell(board,sourceCol, sourceRow))) { return 0; } --j; } if ((targetCol-i==0)&&(targetRow-j==0)) return 1; else return 0; } else if((targetCol<sourceCol)&&(targetRow>sourceRow)) { j=sourceRow; for(i=sourceCol;i>targetCol;--i) { if ((whatIsInTheCell(board,i,j)!=' ') && (whatIsInTheCell(board,i,j)!=whatIsInTheCell(board,sourceCol, sourceRow))) { return 0; } ++j; } if ((targetCol-i==0)&&(targetRow-j==0)) return 1; else return 0; } else if ((targetCol<sourceCol)&&(targetRow<sourceRow)) { j=sourceRow; for(i=sourceCol;i>targetCol;--i) { if ((whatIsInTheCell(board,i,j)!=' ') && (whatIsInTheCell(board,i,j)!=whatIsInTheCell(board,sourceCol, sourceRow))) { return 0; } --j; } if ((targetCol-i==0)&&(targetRow-j==0)) return 1; else return 0; } else { return 0; } return 0; } /* Function isQueenMovable */ /* ----------- */ /* This function checks if a Queen is movable according to the game's rules */ /*---------------------------------------------------------------------------*/ int isQueenMovable(char *board,char sourceCol,int sourceRow,char targetCol, int targetRow) { int i,j; /*checks if the move is along the same column*/ if(targetCol==sourceCol) { /* if up the column*/ if(targetRow>sourceRow) { for(i=sourceRow+1;i<targetRow;++i) { /*checks for the obstacle on the pass */ if (whatIsInTheCell(board,sourceCol,i)!=' ') { return 0; } } return 1; } /*if down the column*/ else { for(i=sourceRow-1;i>targetRow;--i) { if (whatIsInTheCell(board,sourceCol,i)!=' ') { return 0; } } return 1; } } /*if along the same row */ else if (targetRow==sourceRow) { /*to the right*/ if(targetCol>sourceCol) { for(i=sourceCol+1;i<targetCol;++i) { if (whatIsInTheCell(board,i,sourceRow)!=' ') { return 0; } } return 1; } /*to the left*/ else { for(i=sourceCol-1;i>targetCol;--i) { if (whatIsInTheCell(board,i,sourceRow)!=' ') { return 0; } } return 1; } } /*diagonally right up */ else if((targetCol>sourceCol)&&(targetRow>sourceRow)) { j=sourceRow; /*check the diagonal for the obstacles, starting from the source cell*/ for(i=sourceCol;i<targetCol;++i) { if ((whatIsInTheCell(board,i,j)!=' ') && (whatIsInTheCell(board,i,j)!=whatIsInTheCell(board,sourceCol, sourceRow))) { return 0; } ++j; } /*checks whether the target is really on the diagonal*/ if ((targetCol-i==0)&&(targetRow-j==0)) return 1; else return 0; } /*diagonally right down*/ else if ((targetCol>sourceCol)&&(targetRow<sourceRow)) { j=sourceRow; for(i=sourceCol;i<targetCol;++i) { if ((whatIsInTheCell(board,i,j)!=' ') && (whatIsInTheCell(board,i,j)!=whatIsInTheCell(board,sourceCol, sourceRow))) { return 0; } --j; } if ((targetCol-i==0)&&(targetRow-j==0)) return 1; else return 0; } /*diagonally left up*/ else if((targetCol<sourceCol)&&(targetRow>sourceRow)) { j=sourceRow; for(i=sourceCol;i>targetCol;--i) { if ((whatIsInTheCell(board,i,j)!=' ') && (whatIsInTheCell(board,i,j)!=whatIsInTheCell(board,sourceCol, sourceRow))) { return 0; } ++j; } if ((targetCol-i==0)&&(targetRow-j==0)) return 1; else return 0; } /*diagonally left down */ else if ((targetCol<sourceCol)&&(targetRow<sourceRow)) { j=sourceRow; for(i=sourceCol;i>targetCol;--i) { if ((whatIsInTheCell(board,i,j)!=' ') && (whatIsInTheCell(board,i,j)!=whatIsInTheCell(board,sourceCol, sourceRow))) { return 0; } --j; } if ((targetCol-i==0)&&(targetRow-j==0)) return 1; else return 0; } else { return 0; } return 0; } /* Function isKnightMovable */ /* ----------- */ /* This function checks if a Knight is movable according to the game's rules */ /*---------------------------------------------------------------------------*/ int isKnightMovable(char *board,char sourceCol,int sourceRow,char targetCol, int targetRow) { /*checks if the move is within first two columns from each side*/ if((targetCol==sourceCol+1) || (targetCol==sourceCol-1)) { /*cheks if the move is within second two rows from each side */ if((targetRow==sourceRow+2) || (targetRow==sourceRow-2)) { return 1; } else { return 0; } } /*cheks if the move is within second two columns from each side */ else if ((targetCol==sourceCol+2) || (targetCol==sourceCol-2)) { /*checks if the move is within first two rows from each side*/ if((targetRow==sourceRow+1) || (targetRow==sourceRow-1)) { return 1; } else { return 0; } } else { return 0; } return 0; } /* Function isPawnMovable */ /* ----------- */ /* This function checks if a Pawn is movable according to the game's rules */ /*---------------------------------------------------------------------------*/ int isPawnMovable(char *board,char sourceCol,int sourceRow,char targetCol, int targetRow) { /*black and white pawns cant move back*/ if((whatIsInTheCell(board,sourceCol,sourceRow)=='p' && targetRow>sourceRow) || (whatIsInTheCell(board,sourceCol,sourceRow)=='P' && targetRow<sourceRow)) { return 0; } /*checks if the move is along the same column*/ if(targetCol==sourceCol) { /*checks if the move is one cage forward */ /* and if there is any obstacle */ if (((targetRow==sourceRow+1) || (targetRow==sourceRow-1)) &&(whatIsInTheCell(board,targetCol,targetRow)==' ')) return 1; else return 0; } /* Checks if the move is cross move */ else if ((targetCol==sourceCol+1) || (targetCol==sourceCol-1)) { /*Checks if the move is one step cross move and if there is an enemy */ if (((targetRow==sourceRow+1) || (targetRow==sourceRow-1)) &&(whatIsInTheCell(board,targetCol,targetRow)!=' ')) return 1; else return 0; } else { return 0; } return 0; }
C
//This file contains functions that check for valid user input #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <ctype.h> #include "struct_def.h" #include "input.h" bool ValidAction(Board board, UserMove move, int action) { if (board.the_board[move.move_row][move.move_col].visibility == 0) { return action == 0 || action == 1 || action == 2 || action == 3; } else { return action == 0 || action == 1; } } bool MoveConstraintsMet(Board board, UserMove move) { return move.move_row < board.num_rows && move.move_col < board.num_cols && move.move_row >= 0 && move.move_col >= 0; } //checks to see if format of last scanf performed is valid bool IsValidFormatting(int numArgsRead, int numArgsNeeded) { bool validFormat = (numArgsRead == numArgsNeeded); char lastChar; do { scanf("%c", &lastChar); if (!isspace(lastChar)) { //something besides white space appeared after expected input validFormat = false; } } while (lastChar != '\n'); //search until end of line return validFormat; } bool IsValidMove(int numArgsRead, int numArgsNeeded, Board board, UserMove move) { return IsValidFormatting(numArgsRead, numArgsNeeded) && MoveConstraintsMet(board, move); }
C
// Linked List Implementation in C #include <stdio.h> #include <malloc.h> struct Node { char data; struct Node *next; }; void Push(struct Node **topPtr, char el) { struct Node *temp = (struct Node *)malloc(sizeof(struct Node)); temp->data = el; temp->next = NULL; if (*topPtr == NULL) { *topPtr = temp; } else { temp->next = *topPtr; *topPtr = temp; } } char Pop(struct Node **topPtr) { if (*topPtr == NULL) { printf("\n****ERROR****\n-----------UNDERFLOW-----------\n"); return '\0'; } struct Node *ptr = *topPtr; int retVal = ptr->data; *topPtr = ptr->next; free(ptr); return retVal; } char Top(struct Node **topPtr) { return (*topPtr)->data; } int isEmpty(struct Node **topPtr) { if (*topPtr == NULL) return 1; else return 0; } void ReverseString(struct Node **topPtr, char *myStr) { int i = 0; while (myStr[i] != '\0') { Push(topPtr, myStr[i++]); } i = 0; while (!isEmpty(topPtr)) { myStr[i++] = Pop(topPtr); } } int main() { struct Node *top; top = NULL; char myStr[50]; printf("Enter a String \n"); scanf("%s", myStr); ReverseString(&top, myStr); printf("Reversed String is %s\n", myStr); return 0; }
C
#include <stdio.h> #include <stdlib.h> // dizi elerini toplama // int main() { int i , toplam=0; int a[8]={2,3,0,-6,55,987,423,-2}; for(i=0; i<8; i++) toplam = toplam + a[i]; printf("Dizideki elemanlarin toplami: %d\n",toplam); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include "dynarray.h" // DynArray impl void DynArray_deinit(DynArray *darray) { free(darray->arr); } void DynArray_add(DynArray *darray, char newValue) { darray->arr[darray->length] = newValue; darray->length += 1; // realloc mem if (darray->length == darray->cap) { int newcap = darray->cap * 2; char *newarr = realloc(darray->arr, sizeof(char) * newcap); if (newarr == NULL) { free(darray->arr); fprintf(stderr, "Reallocating memory error\n"); abort(); } printf("Reallocated from %i to %i\n", darray->cap, newcap); darray->arr = newarr; darray->cap = newcap; } } void DynArray_print(const DynArray *darray) { for (int i = 0; i < darray->length; i++) { printf("%c,", darray->arr[i]); } printf("\n"); } void DynArray_init(DynArray *darray) { darray->cap = 4; darray->arr = malloc(sizeof(char) * darray->cap); if (darray == NULL) { fprintf(stderr, "Allocating memory error\n"); abort(); } darray->length = 0; } //
C
/* Titouan Teyssier - 11/27/16 */ #include <stdlib.h> #include "list_ptr.h" int areEqual (t_pos d1, t_pos d2) { return (d1.line == d2.line && d1.col == d2.col); } typedef struct element { struct element * next; struct element * prev; t_pos data; } t_element; t_element * gFlag; t_element * gCurrElt; int gNbElt; void listPtr_init (void) { gFlag = malloc (sizeof(t_element)); gFlag -> next = gFlag -> prev = gCurrElt = gFlag; gNbElt = 0; } int listPtr_isEmpty (void) { return gFlag -> next == gFlag; } int listPtr_isOut (void) { return gCurrElt == gFlag; } void listPtr_move2end (void) { gCurrElt = gFlag -> prev; } void listPtr_move2head (void) { gCurrElt = gFlag -> next; } void listPtr_readData (t_pos * data) { if (gCurrElt != gFlag) {// not out of list *data = gCurrElt -> data; } } void listPtr_removeElt (void) { t_element * tmp = NULL; if (gCurrElt != gFlag) {// not out of list tmp = gCurrElt; // redo the chain gCurrElt -> next -> prev = gCurrElt -> prev; gCurrElt -> prev -> next = gCurrElt -> next; // put the current element on the left gCurrElt = gCurrElt -> prev; free(tmp); tmp = NULL; } } void listPtr_removeList (void) { listPtr_move2end(); while (gCurrElt != gFlag) listPtr_removeElt(); } void listPtr_next (void) { if (gCurrElt != gFlag) gCurrElt = gCurrElt -> next; } void listPtr_prev (void) { if (gCurrElt != gFlag) gCurrElt = gCurrElt -> prev; } void listPtr_appendLeft (t_pos data) { t_element * tmp = malloc (sizeof (t_element)); tmp -> data = data; // i dont use the fact that if the list is empty then gFlag = gCurrElt because it's clearer that way. if (listPtr_isEmpty()) { tmp -> next = gFlag; tmp -> prev = gFlag; gFlag -> next = tmp; gFlag -> prev = tmp; gCurrElt = tmp; } else if (!listPtr_isOut()) { tmp -> prev = gCurrElt -> prev; tmp -> next = gCurrElt; gCurrElt -> prev -> next = tmp; gCurrElt -> prev = tmp; gCurrElt = tmp; } else { free (tmp); tmp = NULL; } } void listPtr_appendRight (t_pos data) { t_element * tmp = malloc (sizeof (t_element)); tmp -> data = data; // i dont use the fact that if the list is empty then gFlag = gCurrElt because it's clearer that way. if (listPtr_isEmpty()) { tmp -> next = gFlag; tmp -> prev = gFlag; gFlag -> next = tmp; gFlag -> prev = tmp; gCurrElt = tmp; } else if (!listPtr_isOut()) { tmp -> prev = gCurrElt; tmp -> next = gCurrElt -> next; gCurrElt -> next -> prev = tmp; gCurrElt -> next = tmp; gCurrElt = tmp; } else { free (tmp); tmp = NULL; } } void listPtr_appendEnd (t_pos data) { listPtr_move2end(); listPtr_appendRight(data); } void listPtr_appendHead (t_pos data) { listPtr_move2head(); listPtr_appendLeft(data); } int listPtr_isInList (t_pos data) { t_pos cmp; listPtr_move2head(); while (!listPtr_isOut()) { listPtr_readData(&cmp); if (areEqual(cmp, data)) return 1; listPtr_next(); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_split.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dkozyr <dkozyr@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/15 13:41:51 by dkozyr #+# #+# */ /* Updated: 2019/04/15 14:30:40 by dkozyr ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include <unistd.h> #include <stdio.h> int is_space(char c) { return (c == ' ' || (c >= 9 && c <= 13)); } int count_words(char *str) { int count; int i; count = 0; i = -1; while (str[++i] != '\0') if ((is_space(str[i - 1]) && !is_space(str[i])) || (!is_space(str[0]) && i == 0)) count++; return (count); } char *create_word(char *str, int start) { char *word; int i; int j; i = start; j = 0; word = (char *)malloc(sizeof(char) * (i - start + 1)); while (str[i] != '\0' && !(is_space(str[i]))) { word[j] = str[i]; j++; i++; } word[j] = '\0'; return (word); } char **ft_split(char *str) { char **s; int i; int j; int words; i = 0; j = 0; words = count_words(str); s = (char **)malloc(sizeof(char*) * (words + 1)); while (is_space(str[i])) i++; while (str[i] != '\0') { s[j] = create_word(str, i); j++; while (!is_space(str[i])) i++; while (is_space(str[i])) i++; } s[j] = NULL; return (s); }
C
/*! @header JSON @abstract @discussion JSON parsing&generation. Supports string, number, dictionary & array */ #ifndef __JSON_H_ #define __JSON_H_ #include "primitive_types.h" #include "dictionary.h" #include "array.h" /*! Parses a json string and returns the root object */ Obj_t *parseJSON(const char *aJsonStr); /*! Creates a JSON string from an object */ bool objToJSON(Obj_t *aObj, char *aoBuf, size_t aBufLen); #endif
C
#include <stdio.h> int main() { int n, s; int m, c = 0; printf("Enter the number \n"); scanf("%d", &n); s = n; while (n > 0) { m = n % 10; c = c + (m * m * m); n = n / 10; } if (c == s) { printf("Armstrong=%d\n", s); } else { printf("Not Armstrong=%d\n", c); } return 0; }
C
/* * Modulo que implemeta la logica de lectura del file system FAT12 */ #include <sodero/disquete.h> #include <sodero/syscalls.h> #include <fat.h> #ifdef DEBUG static void dump_BPB (); #endif /** * El sector numero cero del disco (Bios Parameter Block) */ BPB* sector_booteo; // el BPB /** * La tabla de FAT ( donde se encuentra la informacion de los clusters ) */ byte* fat; // la tabla FAT /** * leer_sector_logico: lee un sector logico del disquete * * @param sector_logico sector en formato LBA a leer * @param buffer direccion de memoria donde se lee * * @return estado de la lectura */ int leer_sector_logico ( int sector_logico, void* buffer ) { dword pista, cabeza, sector; word spp = sector_booteo->BPB_sectores_por_pista; word nc = sector_booteo->BPB_numero_cabezas; pista = ( sector_logico - 1 ) / ( spp * nc ); cabeza = 1 & ( ( sector_logico - 1 ) / spp ); sector = 1 + ( ( sector_logico - 1 ) % spp); return leer_sector ( cabeza, pista, sector, buffer ); } /** * cargar_BPB: Carga el BIOS Parameter Block en memoria (en una variable global) * @param sector_booteo direccion en memoria de la variable conteniendo los * datos a leer * * @return el estado de la operacion */ int cargar_BPB (BPB* sector_booteo) { char* buffer; buffer = (char*) sys_alocar (512); if ( leer_sector ( 0, 0, 1, buffer ) == LECTURA_ERRONEA ) { return ERROR; } copiar_memoria ( buffer, sector_booteo, sizeof (BPB) ); return OK; } /** * cargar_fat: Carga la tabla FAT en memoria (en una variable global) * * @return el estado de la operacion */ int cargar_fat() { int indice; int tamanio_fat; dword sector_fat; if ( sector_booteo == NULL ) { if ( cargar_BPB (sector_booteo) == ERROR ) { imprimir ("Error cargando el sector de booteo\n"); return ERROR; } } // obtengo el tamanio de la fat en bytes tamanio_fat = sector_booteo->BPB_tamanio_FAT * 512; // le aloco memoria fat = (byte*) sys_alocar ( tamanio_fat ); // inicializo la FAT con ceros setear_memoria ( fat, 0, tamanio_fat ); // obtengo el primer sector (LOGICO) donde comienza la tabla FAT // (el primer sector es el del BPB, luego del cual vienen los sectores // reservados, y a continuacion la tabla FAT). sector_fat = sector_booteo->BPB_cant_sectores_reservados + 1; // leo los N sectores que conforman la tabla FAT imprimir ( "Cargando FAT" ); for ( indice = 0; indice < sector_booteo->BPB_tamanio_FAT; indice++ ) { imprimir ( "." ); /* * sector_fat es un sector logico, el cual antes de leerlo hay que * trasnformarlo a CHS. * fat es el buffer donde leemos, pero hay que ir incrementandolo por * cada lectura(la primera vez (fat), la segunda (fat+512), y asi... */ if ( leer_sector_logico (sector_fat, fat + indice * 512) == LECTURA_ERRONEA ) { imprimir ( "Error al leer la tabla fat!\n" ); return ERROR; } // leo el siguiente sector logico sector_fat++; } imprimir ( "\n" ); #ifdef DEBUG // el MediaID es 0xF0 para disquettes! imprimir ( "FAT Cargada, MediaID: 0x%xb\n", *fat ); #endif return OK; } /** * inicializa_fat: Setea el BPB y la FAT en NULL para que actuen como flags * (asi se cargan una unica vez) */ void inicializa_fat () { sector_booteo = NULL; fat = NULL; } /** * test_fat: Funcion de prueba utilizada durante la etapa de desarrollo. */ void test_fat() { if ( cargar_fat () == ERROR ) { imprimir ("Error cargando la tabla FAT\n"); return; } #ifdef DEBUG dump_BPB(); #endif } /** * Muestra el contenido del BPB */ #ifdef DEBUG static void dump_BPB () { sector_booteo->BS_nombre_OEM[7] = '\0'; imprimir ( "nombre_OEM: '%s'\n", sector_booteo->BS_nombre_OEM ); imprimir ( "bytes_por_sector: 0x%xw\n",sector_booteo->BPB_bytes_por_sector ); imprimir ( "sec_cluster: 0x%xb\n", sector_booteo->BPB_sectores_por_cluster ); imprimir ("sec_resev: 0x%xw\n", sector_booteo->BPB_cant_sectores_reservados); imprimir ( "cant_FAT: 0x%xb\n", sector_booteo->BPB_cant_FAT ); imprimir ( "entr_root: 0x%xw\n", sector_booteo->BPB_cant_entradas_root ); imprimir ( "cant_sectores: 0x%xw\n",sector_booteo->BPB_cant_sectores_FAT16 ); imprimir ( "media: 0x%xb\n", sector_booteo->BPB_media ); imprimir ( "tamanio_FAT: 0x%xw\n", sector_booteo->BPB_tamanio_FAT ); imprimir ( "sect_pista: 0x%xw\n", sector_booteo->BPB_sectores_por_pista ); imprimir ( "nro_cabezas: 0x%xw\n", sector_booteo->BPB_numero_cabezas ); imprimir ( "sect_ocultos: 0x%x\n", sector_booteo->BPB_sectores_ocultos ); imprimir ( "sect_FAT32: 0x%x\n", sector_booteo->BPB_total_sectores_FAT32 ); imprimir ( "nro_disp: 0x%xb\n", sector_booteo->BS_numero_dispositivo ); imprimir ( "reservado: 0x%xb\n", sector_booteo->BS_reservado ); imprimir ( "firma: 0x%xb\n", sector_booteo->BS_bootsig ); imprimir ( "id_volumen: 0x%x\n", sector_booteo->BS_id_volumen ); sector_booteo->BS_etiqueta_volumen [10] = '\0'; imprimir ( "etiqueta: %s\n", sector_booteo->BS_etiqueta_volumen ); sector_booteo->BS_tipo_filesystem [7] = '\0'; imprimir ( "tipo_filesystem: %s\n", sector_booteo->BS_tipo_filesystem ); } #endif
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* unicode.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tbehra <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/05/01 15:27:32 by tbehra #+# #+# */ /* Updated: 2018/05/10 10:52:06 by tbehra ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" int check_strong_bit(unsigned int val) { int c; if (val > MAX_UNICODE_VAL) return (0); c = 0; while (val) { val >>= 1; c++; } return (c); } int four_bytes(char *to_w, wchar_t c, int *i_to_w, int max_i_to_w) { if (*i_to_w + 3 >= max_i_to_w) return (0); to_w[*i_to_w + 3] = LEFT_BIT | (SIX_RIGHTEST_BITS & c); c >>= 6; to_w[*i_to_w + 2] = LEFT_BIT | (SIX_RIGHTEST_BITS & c); c >>= 6; to_w[*i_to_w + 1] = LEFT_BIT | (SIX_RIGHTEST_BITS & c); c >>= 6; to_w[*i_to_w] = FOUR_LEFTEST_BITS | (THREE_RIGHTEST_BITS & c); *i_to_w += 4; return (1); } int three_bytes(char *to_w, wchar_t c, int *i_to_w, int max_i_to_w) { if (*i_to_w + 2 >= max_i_to_w) return (0); to_w[*i_to_w + 2] = LEFT_BIT | (SIX_RIGHTEST_BITS & c); c >>= 6; to_w[*i_to_w + 1] = LEFT_BIT | (SIX_RIGHTEST_BITS & c); c >>= 6; to_w[*i_to_w] = THREE_LEFTEST_BITS | (FOUR_RIGHTEST_BITS & c); *i_to_w += 3; return (1); } int two_bytes(char *to_w, wchar_t c, int *i_to_w, int max_i_to_w) { if (*i_to_w + 1 >= max_i_to_w) return (0); to_w[*i_to_w + 1] = LEFT_BIT | (SIX_RIGHTEST_BITS & c); c = c >> 6; to_w[*i_to_w] = TWO_LEFTEST_BITS | (FIVE_RIGHTEST_BITS & c); *i_to_w += 2; return (1); } int putwchar_str(char *to_w, wchar_t c, int *i_to_w, t_conv_spec *cs) { int nb_bits; int max_i_to_w; if (cs->precision != UNDEFINED) max_i_to_w = cs->precision; else max_i_to_w = INT_MAX; nb_bits = check_strong_bit(c); if (nb_bits == -1) return (0); if (nb_bits <= 7) { if (*i_to_w >= max_i_to_w) return (0); to_w[*i_to_w] = c; *i_to_w += 1; return (1); } else if (nb_bits <= 11) return (two_bytes(to_w, c, i_to_w, max_i_to_w)); else if (nb_bits <= 16) return (three_bytes(to_w, c, i_to_w, max_i_to_w)); else if (nb_bits <= 21) return (four_bytes(to_w, c, i_to_w, max_i_to_w)); return (0); }
C
/***************************************************************************** * life.c * The original sequential implementation resides here. * Do not modify this file, but you are encouraged to borrow from it ****************************************************************************/ #include "life.h" #include "util.h" /** * Swapping the two boards only involves swapping pointers, not * copying values. */ #define SWAP_BOARDS( b1, b2 ) do { \ char* temp = b1; \ b1 = b2; \ b2 = temp; \ } while(0) //#define BOARD( __board, __i, __j ) (__board[(__i) + LDA*(__j)]) #define BOARD( __board, __i, __j ) (__board[(__j) + LDA*(__i)]) void *thread_board(void * vargp){ int curgen, i, j, ii, jj; thread_args targs = *((thread_args *)vargp); int start_i, start_j; int quadrant = targs.quadrant; int nrows = targs.nrows; int ncols = targs.ncols; char* outboard = targs.outboard; char* inboard = targs.inboard; int gens_max = targs.gens_max; pthread_barrier_t * barrier = targs.barrier; int block_size; if(ncols>=512) block_size = 256; else block_size = ncols/2; if(quadrant == 0 || quadrant == 1) start_i = 0; else start_i = nrows/2; if(quadrant == 0 || quadrant == 2) start_j = 0; else start_j = ncols/2; int isouth, inorth, jeast, jwest; char neighbor_count; int LDA = ncols; unsigned int mask = ncols - 1; /* HINT: you'll be parallelizing these loop(s) by doing a geometric decomposition of the output */ for (curgen = 0; curgen < gens_max; curgen++) { for (i = start_i; i < start_i + nrows/2; i+= block_size) { for (j = start_j; j < start_j + ncols/2; j+= block_size) { for (ii = i; ii<i+block_size;ii++) { //isouth = mod (ii+1, nrows); // inorth = mod (ii-1, nrows); isouth = (ii+1)&mask; inorth = (ii-1)&mask; for (jj= j; jj<j+block_size;jj++){ //jwest = mod (jj-1, ncols); //jeast = mod (jj+1, ncols); jwest = (jj-1)&mask; jeast = (jj+1)&mask; neighbor_count = BOARD (inboard, inorth, jwest) + BOARD (inboard, inorth, jj) + BOARD (inboard, inorth, jeast) + BOARD (inboard, ii, jwest) + BOARD (inboard, ii, jeast) + BOARD (inboard, isouth, jwest) + BOARD (inboard, isouth, jj) + BOARD (inboard, isouth, jeast); //BOARD(outboard, ii, jj) = alivep (neighbor_count, BOARD (inboard, ii, jj)); BOARD(outboard, ii, jj) = (!BOARD (inboard, ii, jj) && (neighbor_count == (char) 3)) ||(BOARD(inboard, ii, jj) && (neighbor_count >= 2) && (neighbor_count <= 3)); } } } } pthread_barrier_wait(barrier); SWAP_BOARDS( outboard, inboard ); } return NULL; } char* optimized_game_of_life (char* outboard, char* inboard, const int nrows, const int ncols, const int gens_max) { /* HINT: in the parallel decomposition, LDA may not be equal to nrows! */ int i; pthread_t thrd[NUM_THREADS]; thread_args targs[NUM_THREADS]; pthread_barrier_t barrier; pthread_barrier_init(&barrier, NULL, NUM_THREADS); for(i=0; i<NUM_THREADS;i++){ targs[i].barrier = &barrier; targs[i].quadrant = i; targs[i].inboard = inboard; targs[i].outboard = outboard; targs[i].nrows = nrows; targs[i].ncols = ncols; targs[i].gens_max = gens_max; pthread_create(&thrd[i], NULL, thread_board, (void*)&(targs[i])); } for(i=0; i<NUM_THREADS;i++){ pthread_join(thrd[i], NULL); } /* * We return the output board, so that we know which one contains * the final result (because we've been swapping boards around). * Just be careful when you free() the two boards, so that you don't * free the same one twice!!! */ return inboard; }
C
/* * This is sample code generated by rpcgen. * These are only templates and you can use them * as a guideline for developing your own functions. */ #include "calc.h" float * calc_1_svc(calc_in *argp, struct svc_req *rqstp) { static float result; /* * insert server code here */ printf("%d", argp->z); if(argp->z == 1){ result = argp->x + argp->y;} else if(argp->z == 2){ result = argp->x - argp->y;} else if(argp->z==3){ result = argp->x * argp->y;} else if(argp->z == 4){ result = argp->x / argp->y;} return &result; }
C
#include <stdio.h> #include <sys/types.h> #include <signal.h> void deroute(int no) { switch(no) { case SIGCHLD: // mort d'un fils printf("Un fils est mort !\n"); wait(NULL); case SIGTERM: printf("Vous pouvez pas utiliser SIGTERM\n"); break; case SIGINT: printf("Vous pouvez pas utiliser SIGINT\n"); break; } // sw } // deroute int main () { int fk; signal(SIGCHLD, deroute); signal(SIGTERM, deroute); signal(SIGINT, deroute); fk = fork(); switch(fk) { case 0: // fils printf("Je suis le fils et je meurs de suite\n"); return 0; } // sw while (1) pause(); } // main
C
// ## Prologue // // This is the interface to a simple and general lexer function for // c-like languages. // See the source file `lex.c` for more information. #ifndef NS #define NS(id) id #endif // ## Fundamental Types // ### Context Structure // The context of our lexer includes two kinds of buffers: // A variable frontbuffer, which acts as a window to the constant // backbuffer and changes in size and position as we process the // contents of the latter. typedef enum { NS(Success), NS(Fail), NS(Undecided), NS(End) } NS(State); typedef struct { char *buf; size_t sz, cap, off; NS(State) state; } NS(Ctx); // ### Token Structure // The emitted tokens include a type a success-indicating state and an // optional length. // We operate on a small set of tokens types. // Keywords, typenames and identifiers are summarized under the // `Identifier` token type. All kinds of punctuations have a common // type, comments are also understood as punctuation. typedef struct { enum { NS(Undefined), NS(Number), NS(Identifier), NS(Whitespace), NS(String), NS(Character), NS(Punctuation), NS(Directive) } type; size_t off; size_t len; unsigned long long int t; } NS(Tok); // ## Interface int lex(NS(Ctx) *const, NS(Tok) *, int); #undef NS
C
/* ** Author: Team The HPC Lab ** Email : admin@thehpclab.com ** Details: A program to demonstrate prefetching features on Xeon and Xeon Phi ** We have two data arrays say A and B. Both containing random numbers ** in some fashion. The values stored in array A is related to array B ** in some way. The logic of the algorithm requires to scan the array A ** linearly one by one and do processing as outlined below ** Pseudo code ** for(i = 1; i < size; i++) ** { ** int indexA = i; ** int indexB = A[i]; ** B[indexB]*=indexA; ** } ** ** Example: say A[30]=40, then indexA = 30, indexB = 40, we visit B[40] ** and multiply B[40] with 30; */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <time.h> void randomize(int32_t* arr, int32_t size) { for(uint32_t i=0;i<size;i++) { arr[i]=i; } //intialize the random number generator with current as seed srand( time(NULL) ); int temp; int random; /* Swap the numbers in array using random seed, you can always write a faster swap function ** I am not doing it to keep things simple and explicit **/ for(uint32_t i=0;i<size;i++) { random = rand()%size; temp = arr[i]; arr[i]=arr[random]; arr[random] = temp; } } int main(int argc, char *argv[]) { //Program takes size of the array as argument if(argc < 3) exit(1); int32_t arrSize = atoi(argv[1]); int32_t prefetchDistance = atoi(argv[2]); int32_t *A = (uint32_t*) malloc(sizeof(uint32_t)*arrSize); int32_t *B = (uint32_t*) malloc(sizeof(uint32_t)*arrSize); //initialize and randomize the input data randomize(A,arrSize); randomize(B,arrSize); // Lets create time storing variables double start, startNoPrefetch, startPrefetch,end; uint32_t indexB; //first we run the code directly start = clock(); for(uint32_t i=0;i<arrSize;i++) { indexB = A[i]; B[indexB]*=i; } //lets deliberately disable prefetching startNoPrefetch = clock(); #pragma noprefetch A,B for(uint32_t i=0;i<arrSize;i++) { indexB = A[i]; B[indexB]*=i; } startPrefetch = clock(); //lets now use prefetching for(uint32_t i=0;i<arrSize;i++) { if(i+prefetchDistance < arrSize) { int prefetchIndexB = A[i+prefetchDistance]; __builtin_prefetch(&(B[prefetchIndexB]),1,1); } indexB = A[i]; B[indexB]*=i; } end = clock(); //Print the timings printf("\n Direct %g", ((startNoPrefetch - start)/CLOCKS_PER_SEC)); printf("\n No Prefetch %g", ((startPrefetch - startNoPrefetch)/CLOCKS_PER_SEC ) ); printf("\n Manual Prefetch %g", ((end - startPrefetch) /CLOCKS_PER_SEC)); //clean up free(A); free(B); return 0; }
C
void sort(int [] ser) { int n=sizeof(ser)/sizeof(ser[0]); int i; int j; for(i=0;i<n;i++) { for(j=0;j<n-i-1;j++) { if(ser[j]>ser[j+1]) { t=ser[j]; ser[j]=ser[j+1]; ser[j+1]=t; } } } }
C
//Program to display Circle pattern by accepting radius #include<stdio.h> #include<math.h> int main() { int r,d,x,y,i,j; printf("Enter Radius of circle: "); scanf("%d",&r); d=2*r+1; //+1 for including centre char a[d][d]; x=r,y=r; //Co-ordinates of Centre for(i=0;i<d;i++) for(j=0;j<d;j++) a[i][j]='.'; float dist; for(i=0;i<d;i++){ for(j=0;j<d;j++){ dist=sqrt(pow(x-i,2)+pow(y-j,2)); if(dist>=r-0.5 && dist<=r+0.5) //dist needs to be only approximately equal to r a[i][j]='#'; } } printf("\n\n"); for(i=0;i<d;i++){ for(j=0;j<d;j++){ printf("%c ",a[i][j]); } printf("\n"); } printf("\n\n"); return 0; } //Code written by Tawanjot Singh ;')
C
#include <stdio.h> #include "stack.h" int main (int argc, char* argv[]){ stack* stk = stk_create_stack(); contact* tmp1 = stk_create_node("Inspecteur Lestrad", "01 01 01 01 01"); stk_push (stk,tmp1); contact* tmp2 = stk_create_node("Janine", "01 03 03 03 40"); stk_push (stk,tmp2); contact* tmp3 = stk_create_node("Inspecteur GREGSON", "05 02 02 01 01"); stk_push (stk,tmp3); contact* tmp = stk_pop(stk); stk_display_contact(tmp); tmp = stk_pop(stk); stk_display_contact(tmp); tmp = stk_pop(stk); stk_display_contact(tmp); tmp = stk_pop(stk); stk_display_contact(tmp); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct node{ char word[100]; int len; struct node*next; }Node; int text(Node*head, int len); int len(Node *head); int main(int argc, char *argv[]){ if(argc!=2){ printf("Number of arguments are wrong\n"); return 0; } char array[100]; FILE*ifile; ifile= fopen(argv[1],"r"); Node head; Node * itr= &head; while(fscanf(ifile, "%s",array) != EOF){ Node *temp =NULL; temp=(Node*)malloc(sizeof(Node)); itr->next=temp; strcpy(temp->word,array); temp->len = strlen(array); itr= temp; } fclose(ifile); text(&head,len(&head)); return 0; } int len(Node * head){ int l=0; Node *crnt = head; while(crnt != NULL){ if(crnt-> len > l){ l=crnt->len; } crnt = crnt-> next; } return l; } int text(Node *head, int len){ while(len>0){ while(head != NULL){ if(head->len == len){ printf("%s\n", head->word); return 0; } head = head-> next; } len--; } }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <complex.h> #include <string.h> #include "readNprintPhi.h" #include "matrix.h" void printPhi(char path[100], char ps, _Complex double ***phi, int iconf, int nxi, int mt, int Lvol){ /* output FILE */ FILE *fout; /* file to save result */ char what[10]; if (ps == 'p') strcpy(what, "phi"); if (ps == 's') strcpy(what, "source"); fprintf(stderr, "conf %i.%i: ...Print %s to some file: %s...\n", iconf, nxi, what, path); /* open and print */ fout = fopen(path, "w"); fprintf(fout, "conf = %i, Nsource = %i, mt = %i\n\n", iconf, nxi, mt); fPrint3D(fout, phi, Lvol, 4, 3); fclose(fout); } int readPhi(char file[100], char ps, _Complex double ***phi, int nxi, int iconf, int Nxi){ char fileNumber[10]; char fileName[100]; FILE *fout; int confread, sourceread; int mt; char what[10]; if (ps == 'p') strcpy(what, "phi"); if (ps == 's') strcpy(what, "source"); /* open propagator file */ strcpy(fileName, file); snprintf(fileNumber, 10, ".%d.%d.%d", iconf, Nxi, nxi); strcat(fileName, fileNumber); /* get proper file name for output file: conf.nr.source */ fout = fopen(fileName, "r"); fprintf(stderr, "conf %i.%i: ...Read %s from file: %s...\n", iconf, nxi, what, fileName); /* read propagator */ phi = readmyOutput(fout, &confread, &sourceread, &mt, phi); /* read prop */ /* close propagator file */ fclose(fout); /* check whether its the right file */ if (confread != iconf){ /* if read vars do not fit to counting vars */ fprintf(stderr, "conf from file does not fit to loop var\n"); fprintf(stderr, "conf_file = %i\n\n", confread); fprintf(stderr, "conf_prog = %i\n\n", iconf); } if (sourceread != nxi){ /* if read vars do not fit to counting vars */ fprintf(stderr, "source from file does not fit to loop var\n"); fprintf(stderr, "source_file = %i\n\n", sourceread); fprintf(stderr, "source_prog = %i\n\n", nxi); } return mt; } /* read my propagator files */ /* to get prop G[n][alpha][a] */ /* additional: get time slice of source mt, sourcenr Nxi and confnr conf */ _Complex double ***readmyOutput(FILE *f, int *conf, int *nxi, int *m0, _Complex double ***out ){ int n_read, alpha_read, a_read; /* int a0, alpha0, m0; */ fscanf(f, "conf = %i, Nsource = %i, mt = %i\n\n", &(*conf), &(*nxi), &(*m0)); fprintf(stderr, "conf %i.%i: mt = %i\n", *conf, *nxi, *m0); do{ /* convention in file: z y x t */ fscanf(f, "A[n=%i][alpha=%i][a=%i] = ", &n_read, &alpha_read, &a_read); fscanf(f, "%lf +i*%lf\n", &(__real__ out[n_read][alpha_read][a_read]), &(__imag__ out[n_read][alpha_read][a_read]) ); }while(!feof(f)); return out; }
C
/* Copyright (c) 2003-2004, Roger Dingledine * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. * Copyright (c) 2007-2021, The Tor Project, Inc. */ /* See LICENSE for licensing information */ /** * \file smartlist_foreach.h * \brief Macros for iterating over the elements of a smartlist_t. **/ #ifndef TOR_SMARTLIST_FOREACH_H #define TOR_SMARTLIST_FOREACH_H /** Iterate over the items in a smartlist <b>sl</b>, in order. For each item, * assign it to a new local variable of type <b>type</b> named <b>var</b>, and * execute the statements inside the loop body. Inside the loop, the loop * index can be accessed as <b>var</b>_sl_idx and the length of the list can * be accessed as <b>var</b>_sl_len. * * NOTE: Do not change the length of the list while the loop is in progress, * unless you adjust the _sl_len variable correspondingly. See second example * below. * * Example use: * <pre> * smartlist_t *list = smartlist_split("A:B:C", ":", 0, 0); * SMARTLIST_FOREACH_BEGIN(list, char *, cp) { * printf("%d: %s\n", cp_sl_idx, cp); * tor_free(cp); * } SMARTLIST_FOREACH_END(cp); * smartlist_free(list); * </pre> * * Example use (advanced): * <pre> * SMARTLIST_FOREACH_BEGIN(list, char *, cp) { * if (!strcmp(cp, "junk")) { * tor_free(cp); * SMARTLIST_DEL_CURRENT(list, cp); * } * } SMARTLIST_FOREACH_END(cp); * </pre> */ /* Note: these macros use token pasting, and reach into smartlist internals. * This can make them a little daunting. Here's the approximate unpacking of * the above examples, for entertainment value: * * <pre> * smartlist_t *list = smartlist_split("A:B:C", ":", 0, 0); * { * int cp_sl_idx, cp_sl_len = smartlist_len(list); * char *cp; * for (cp_sl_idx = 0; cp_sl_idx < cp_sl_len; ++cp_sl_idx) { * cp = smartlist_get(list, cp_sl_idx); * printf("%d: %s\n", cp_sl_idx, cp); * tor_free(cp); * } * } * smartlist_free(list); * </pre> * * <pre> * { * int cp_sl_idx, cp_sl_len = smartlist_len(list); * char *cp; * for (cp_sl_idx = 0; cp_sl_idx < cp_sl_len; ++cp_sl_idx) { * cp = smartlist_get(list, cp_sl_idx); * if (!strcmp(cp, "junk")) { * tor_free(cp); * smartlist_del(list, cp_sl_idx); * --cp_sl_idx; * --cp_sl_len; * } * } * } * </pre> */ #define SMARTLIST_FOREACH_BEGIN(sl, type, var) \ STMT_BEGIN \ int var ## _sl_idx, var ## _sl_len=(sl)->num_used; \ type var; \ for (var ## _sl_idx = 0; var ## _sl_idx < var ## _sl_len; \ ++var ## _sl_idx) { \ var = (sl)->list[var ## _sl_idx]; /** Iterates over the items in smartlist <b>sl</b> in reverse order, similar to * SMARTLIST_FOREACH_BEGIN * * NOTE: This macro is incompatible with SMARTLIST_DEL_CURRENT. */ #define SMARTLIST_FOREACH_REVERSE_BEGIN(sl, type, var) \ STMT_BEGIN \ int var ## _sl_idx, var ## _sl_len=(sl)->num_used; \ type var; \ for (var ## _sl_idx = var ## _sl_len-1; var ## _sl_idx >= 0; \ --var ## _sl_idx) { \ var = (sl)->list[var ## _sl_idx]; #define SMARTLIST_FOREACH_END(var) \ var = NULL; \ (void) var ## _sl_idx; \ } STMT_END /** * An alias for SMARTLIST_FOREACH_BEGIN and SMARTLIST_FOREACH_END, using * <b>cmd</b> as the loop body. This wrapper is here for convenience with * very short loops. * * By convention, we do not use this for loops which nest, or for loops over * 10 lines or so. Use SMARTLIST_FOREACH_{BEGIN,END} for those. */ #define SMARTLIST_FOREACH(sl, type, var, cmd) \ SMARTLIST_FOREACH_BEGIN(sl,type,var) { \ cmd; \ } SMARTLIST_FOREACH_END(var) /** Helper: While in a SMARTLIST_FOREACH loop over the list <b>sl</b> indexed * with the variable <b>var</b>, remove the current element in a way that * won't confuse the loop. */ #define SMARTLIST_DEL_CURRENT(sl, var) \ STMT_BEGIN \ smartlist_del(sl, var ## _sl_idx); \ --var ## _sl_idx; \ --var ## _sl_len; \ STMT_END /** Helper: While in a SMARTLIST_FOREACH loop over the list <b>sl</b> indexed * with the variable <b>var</b>, remove the current element in a way that * won't confuse the loop. */ #define SMARTLIST_DEL_CURRENT_KEEPORDER(sl, var) \ STMT_BEGIN \ smartlist_del_keeporder(sl, var ## _sl_idx); \ --var ## _sl_idx; \ --var ## _sl_len; \ STMT_END /** Helper: While in a SMARTLIST_FOREACH loop over the list <b>sl</b> indexed * with the variable <b>var</b>, replace the current element with <b>val</b>. * Does not deallocate the current value of <b>var</b>. */ #define SMARTLIST_REPLACE_CURRENT(sl, var, val) \ STMT_BEGIN \ smartlist_set(sl, var ## _sl_idx, val); \ STMT_END #endif /* !defined(TOR_SMARTLIST_FOREACH_H) */
C
#include <assert.h> #include <errno.h> #include <getopt.h> #include <math.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "c63.h" #include "tables.h" #define MARKER_START 0xff #define MARKER_DQT 0xdb #define MARKER_SOI 0xd8 #define MARKER_SOS 0xda #define MARKER_SOF0 0xc0 #define MARKER_EOI 0xd9 #define MARKER_DHT 0xc4 #define HUFF_AC_ZERO 16 #define HUFF_AC_SIZE 11 /* Decode VLC token */ static uint8_t get_vlc_token(struct entropy_ctx *c, uint16_t *table, uint8_t *table_sz, int tablelen) { int i, n; uint16_t bits = 0; for (n = 1; n <= 16; ++n) { bits <<= 1; bits |= get_bits(c, 1); /* See if this string matches a token in VLC table */ for (i = 0; i < tablelen; ++i) { if (table_sz[i] < n) { /* Too small token. */ continue; } if (table_sz[i] == n) { if (bits == (table[i] & ((1 << n) - 1))) { /* Found it */ return i; } } } } fprintf(stdout, "VLC token not found.\n"); exit(EXIT_FAILURE); } /* Decode AC VLC token. Optimized VLC decoder that takes advantage of the increasing order of our ACVLC_Size table. Does not work with a general table, so use the unoptimized get_vlc_token. A better approach would be to use an index table. */ static uint8_t get_vlc_token_ac(struct entropy_ctx *c, uint16_t table[HUFF_AC_ZERO][HUFF_AC_SIZE], uint8_t table_sz[HUFF_AC_ZERO][HUFF_AC_SIZE]) { int n, x, y; uint16_t bits = 0; for (n = 1; n <= 16; ++n) { bits <<= 1; bits |= get_bits(c, 1); uint16_t mask = (1 << n) - 1; for (x = 1; x < HUFF_AC_SIZE; ++x) { for (y = 0; y < HUFF_AC_ZERO; ++y) { if (table_sz[y][x] < n) { continue; } else if (table_sz[y][x] > n) { break; } else if (bits == (table[y][x] & mask)) { /* Found it */ return y*HUFF_AC_SIZE + x; } } if (table_sz[x][0] > n) { break; } } /* Check if it's a special token (bitsize 0) */ for (y = 0; y < HUFF_AC_ZERO; y += (HUFF_AC_ZERO-1)) { if (table_sz[y][0] == n && bits == (table[y][0] & mask)) { /* Found it */ return y*HUFF_AC_SIZE; } } } printf("VLC token not found (ac).\n"); exit(EXIT_FAILURE); } /* Decode sign of value from VLC. See Figure F.12 in spec. */ static int16_t extend_sign(int16_t v, int sz) { int vt = 1 << (sz - 1); if (v >= vt) { return v; } int range = (1 << sz) - 1; v = -(range - v); return v; } static void read_block(struct c63_common *cm, int16_t *out_data, uint32_t width, uint32_t height, uint32_t uoffset, uint32_t voffset, int16_t *prev_DC, int32_t cc, int channel) { int i, num_zero=0; uint8_t size; /* Read motion vector */ struct macroblock *mb = &cm->curframe->mbs[channel][voffset/8 * cm->padw[channel]/8 + uoffset/8]; /* Use inter pred? */ mb->use_mv = get_bits(&cm->e_ctx, 1); if (mb->use_mv) { int reuse_prev_mv = get_bits(&cm->e_ctx, 1); if (reuse_prev_mv) { mb->mv_x = (mb-1)->mv_x; mb->mv_y = (mb-1)->mv_y; } else { int16_t val; size = get_vlc_token(&cm->e_ctx, MVVLC, MVVLC_Size, ARRAY_SIZE(MVVLC)); val = get_bits(&cm->e_ctx, size); mb->mv_x = extend_sign(val, size); size = get_vlc_token(&cm->e_ctx, MVVLC, MVVLC_Size, ARRAY_SIZE(MVVLC)); val = get_bits(&cm->e_ctx, size); mb->mv_y = extend_sign(val, size); } } /* Read residuals */ // Linear block in memory int16_t *block = &out_data[uoffset * 8 + voffset * width]; memset(block, 0, 64 * sizeof(int16_t)); /* Decode DC */ size = get_vlc_token(&cm->e_ctx, DCVLC[cc], DCVLC_Size[cc], ARRAY_SIZE(DCVLC[cc])); int16_t dc = get_bits(&cm->e_ctx, size); dc = extend_sign(dc, size); block[0] = dc + *prev_DC; *prev_DC = block[0]; /* Decode AC RLE */ for (i = 1; i < 64; ++i) { uint16_t token = get_vlc_token_ac(&cm->e_ctx, ACVLC[cc], ACVLC_Size[cc]); num_zero = token / 11; size = token % 11; i += num_zero; if (num_zero == 15 && size == 0) { continue; } else if (num_zero == 0 && size == 0) { break; } int16_t ac = get_bits(&cm->e_ctx, size); block[i] = extend_sign(ac, size); } #if 0 int j; static int blocknum; ++blocknum; printf("Dump block %d:\n", blocknum); for(i = 0; i < 8; ++i) { for (j = 0; j < 8; ++j) { printf(", %5d", block[i*8+j]); } printf("\n"); } printf("Finished block\n\n"); #endif } static void read_interleaved_data_MCU(struct c63_common *cm, int16_t *dct, uint32_t wi, uint32_t he, uint32_t h, uint32_t v, uint32_t x, uint32_t y, int16_t *prev_DC, int32_t cc, int channel) { uint32_t i, j, ii, jj; for(j = y*v*8; j < (y+1)*v*8; j += 8) { jj = he-8; jj = MIN(j, jj); for(i = x*h*8; i < (x+1)*h*8; i += 8) { ii = wi-8; ii = MIN(i, ii); read_block(cm, dct, wi, he, ii, jj, prev_DC, cc, channel); } } } void read_interleaved_data(struct c63_common *cm) { int u,v; int16_t prev_DC[3] = {0, 0, 0}; uint32_t ublocks = (uint32_t) (ceil(cm->ypw/(float)(8.0f*2))); uint32_t vblocks = (uint32_t) (ceil(cm->yph/(float)(8.0f*2))); /* Write the MCU's interleaved */ for(v = 0; v < vblocks; ++v) { for(u = 0; u < ublocks; ++u) { read_interleaved_data_MCU(cm, cm->curframe->residuals->Ydct, cm->ypw, cm->yph, YX, YY, u, v, &prev_DC[0], 0, 0); read_interleaved_data_MCU(cm, cm->curframe->residuals->Udct, cm->upw, cm->uph, UX, UY, u, v, &prev_DC[1], 1, 1); read_interleaved_data_MCU(cm, cm->curframe->residuals->Vdct, cm->vpw, cm->vph, VX, VY, u, v, &prev_DC[2], 1, 2); } } } // Define quantization tables void parse_dqt(struct c63_common *cm) { int i; uint16_t size; size = (get_byte(cm->e_ctx.fp) << 8) | get_byte(cm->e_ctx.fp); // Discard size size = size; /* huh? */ for (i = 0; i < 3; ++i) { int idx = get_byte(cm->e_ctx.fp); if (idx != i) { fprintf(stderr, "DQT: Expected %d - got %d\n", i, idx); exit(EXIT_FAILURE); } read_bytes(cm->e_ctx.fp, cm->quanttbl[i], 64); } } // Start of scan void parse_sos(struct c63_common *cm) { uint16_t size; size = (get_byte(cm->e_ctx.fp) << 8) | get_byte(cm->e_ctx.fp); /* Don't care currently */ uint8_t buf[size]; read_bytes(cm->e_ctx.fp, buf, size-2); } // Baseline DCT void parse_sof0(struct c63_common *cm) { uint16_t size; size = (get_byte(cm->e_ctx.fp) << 8) | get_byte(cm->e_ctx.fp); size = size; // Discard size uint8_t precision = get_byte(cm->e_ctx.fp); if (precision != 8) { fprintf(stderr, "Only 8-bit precision supported\n"); exit(EXIT_FAILURE); } uint16_t height = (get_byte(cm->e_ctx.fp) << 8) | get_byte(cm->e_ctx.fp); uint16_t width = (get_byte(cm->e_ctx.fp) << 8) | get_byte(cm->e_ctx.fp); // Discard subsampling info. We assume 4:2:0 uint8_t buf[10]; read_bytes(cm->e_ctx.fp, buf, 10); /* First frame? */ if (cm->framenum == 0) { cm->width = width; cm->height = height; cm->padw[0] = cm->ypw = (uint32_t)(ceil(width/16.0f)*16); cm->padh[0] = cm->yph = (uint32_t)(ceil(height/16.0f)*16); cm->padw[1] = cm->upw = (uint32_t)(ceil(width*UX/(YX*8.0f))*8); cm->padh[1] = cm->uph = (uint32_t)(ceil(height*UY/(YY*8.0f))*8); cm->padw[2] = cm->vpw = (uint32_t)(ceil(width*VX/(YX*8.0f))*8); cm->padh[2] = cm->vph = (uint32_t)(ceil(height*VY/(YY*8.0f))*8); cm->mb_cols = cm->ypw / 8; cm->mb_rows = cm->yph / 8; cm->curframe = 0; } /* Advance to next frame */ destroy_frame(cm->refframe); cm->refframe = cm->curframe; cm->curframe = create_frame(cm, 0, 0); /* Is this a keyframe */ cm->curframe->keyframe = get_byte(cm->e_ctx.fp); } // Define Huffman tables void parse_dht(struct c63_common *cm) { uint16_t size; size = (get_byte(cm->e_ctx.fp) << 8) | get_byte(cm->e_ctx.fp); // XXX: Should be handeled properly. However, we currently only use static // tables uint8_t buf[size]; read_bytes(cm->e_ctx.fp, buf, size-2); } int parse_c63_frame(struct c63_common *cm) { // SOI if (get_byte(cm->e_ctx.fp) != MARKER_START || get_byte(cm->e_ctx.fp) != MARKER_SOI) { fprintf(stderr, "Not an JPEG file\n"); exit(EXIT_FAILURE); } while(1) { int c; c = get_byte(cm->e_ctx.fp); if (c == 0) { c = get_byte(cm->e_ctx.fp); } if (c != MARKER_START) { fprintf(stderr, "Expected marker.\n"); exit(EXIT_FAILURE); } uint8_t marker = get_byte(cm->e_ctx.fp); if (marker == MARKER_DQT) { parse_dqt(cm); } else if (marker == MARKER_SOS) { parse_sos(cm); read_interleaved_data(cm); cm->e_ctx.bit_buffer = cm->e_ctx.bit_buffer_width = 0; } else if (marker == MARKER_SOF0) { parse_sof0(cm); } else if (marker == MARKER_DHT) { parse_dht(cm); } else if (marker == MARKER_EOI) { return 1; } else { fprintf(stderr, "Invalid marker: 0x%02x\n", marker); exit(EXIT_FAILURE); } } return 1; } /* Motion compensation for 8x8 block */ static void mc_block_8x8_dec(struct c63_common *cm, int mb_x, int mb_y, uint8_t *predicted, uint8_t *ref, int cc) { struct macroblock *mb = &cm->curframe->mbs[cc][mb_y * cm->padw[cc]/8 + mb_x]; if (!mb->use_mv) { return; } int left = mb_x * 8; int top = mb_y * 8; int right = left + 8; int bottom = top + 8; int w = cm->padw[cc]; /* Copy block from ref mandated by MV */ int x, y; for (y = top; y < bottom; ++y) { for (x = left; x < right; ++x) { predicted[y*w+x] = ref[(y + mb->mv_y) * w + (x + mb->mv_x)]; } } } void c63_motion_compensate_dec(struct c63_common *cm) { int mb_x, mb_y; /* Luma */ for (mb_y = 0; mb_y < cm->mb_rows; ++mb_y) { for (mb_x = 0; mb_x < cm->mb_cols; ++mb_x) { mc_block_8x8_dec(cm, mb_x, mb_y, cm->curframe->predicted->Y, cm->refframe->recons->Y, 0); } } /* Chroma */ for (mb_y = 0; mb_y < cm->mb_rows / 2; ++mb_y) { for (mb_x = 0; mb_x < cm->mb_cols / 2; ++mb_x) { mc_block_8x8_dec(cm, mb_x, mb_y, cm->curframe->predicted->U, cm->refframe->recons->U, 1); mc_block_8x8_dec(cm, mb_x, mb_y, cm->curframe->predicted->V, cm->refframe->recons->V, 2); } } } static void transpose_block_dec(float *in_data, float *out_data) { int i, j; for (i = 0; i < 8; ++i) { for (j = 0; j < 8; ++j) { out_data[i*8+j] = in_data[j*8+i]; } } } static void idct_1d_dec(float *in_data, float *out_data) { int i, j; for (i = 0; i < 8; ++i) { float idct = 0; for (j = 0; j < 8; ++j) { idct += in_data[j] * dctlookup[i][j]; } out_data[i] = idct; } } static void scale_block_dec(float *in_data, float *out_data) { int u, v; for (v = 0; v < 8; ++v) { for (u = 0; u < 8; ++u) { float a1 = !u ? ISQRT2 : 1.0f; float a2 = !v ? ISQRT2 : 1.0f; /* Scale according to normalizing function */ out_data[v*8+u] = in_data[v*8+u] * a1 * a2; } } } static void dequantize_block_dec(float *in_data, float *out_data, uint8_t *quant_tbl) { int zigzag; for (zigzag = 0; zigzag < 64; ++zigzag) { uint8_t u = zigzag_U[zigzag]; uint8_t v = zigzag_V[zigzag]; float dct = in_data[zigzag]; /* Zig-zag and de-quantize */ out_data[v*8+u] = (float) round((dct * quant_tbl[zigzag]) / 4.0); } } void dequant_idct_block_8x8_dec(int16_t *in_data, int16_t *out_data, uint8_t *quant_tbl) { float mb[8*8] __attribute((aligned(16))); float mb2[8*8] __attribute((aligned(16))); int i, v; for (i = 0; i < 64; ++i) { mb[i] = in_data[i]; } dequantize_block_dec(mb, mb2, quant_tbl); scale_block_dec(mb2, mb); /* Two 1D inverse DCT operations with transpose */ for (v = 0; v < 8; ++v) { idct_1d_dec(mb+v*8, mb2+v*8); } transpose_block_dec(mb2, mb); for (v = 0; v < 8; ++v) { idct_1d_dec(mb+v*8, mb2+v*8); } transpose_block_dec(mb2, mb); for (i = 0; i < 64; ++i) { out_data[i] = mb[i]; } } void dequantize_idct_row_dec(int16_t *in_data, uint8_t *prediction, int w, int h, int y, uint8_t *out_data, uint8_t *quantization) { int x; int16_t block[8*8]; /* Perform the dequantization and iDCT */ for(x = 0; x < w; x += 8) { int i, j; dequant_idct_block_8x8_dec(in_data+(x*8), block, quantization); for (i = 0; i < 8; ++i) { for (j = 0; j < 8; ++j) { /* Add prediction block. Note: DCT is not precise - Clamp to legal values */ int16_t tmp = block[i*8+j] + (int16_t)prediction[i*w+j+x]; if (tmp < 0) { tmp = 0; } else if (tmp > 255) { tmp = 255; } out_data[i*w+j+x] = tmp; } } } } void dequantize_idct_dec(int16_t *in_data, uint8_t *prediction, uint32_t width, uint32_t height, uint8_t *out_data, uint8_t *quantization) { int y; for (y = 0; y < height; y += 8) { dequantize_idct_row_dec(in_data+y*width, prediction+y*width, width, height, y, out_data+y*width, quantization); } } void decode_c63_frame(struct c63_common *cm, FILE *fout) { /* Motion Compensation */ if (!cm->curframe->keyframe) { c63_motion_compensate_dec(cm); } /* Decode residuals */ dequantize_idct_dec(cm->curframe->residuals->Ydct, cm->curframe->predicted->Y, cm->ypw, cm->yph, cm->curframe->recons->Y, cm->quanttbl[0]); dequantize_idct_dec(cm->curframe->residuals->Udct, cm->curframe->predicted->U, cm->upw, cm->uph, cm->curframe->recons->U, cm->quanttbl[1]); dequantize_idct_dec(cm->curframe->residuals->Vdct, cm->curframe->predicted->V, cm->vpw, cm->vph, cm->curframe->recons->V, cm->quanttbl[2]); #ifndef C63_PRED /* Write result */ dump_image(cm->curframe->recons, cm->width, cm->height, fout); #else /* To dump the predicted frames, use this instead */ dump_image(cm->curframe->predicted, cm->width, cm->height, fout); #endif ++cm->framenum; } static void print_help(int argc, char **argv) { printf("Usage: %s input.c63 output.yuv\n\n", argv[0]); printf("Tip! Use mplayer to playback raw YUV file:\n"); printf("mplayer -demuxer rawvideo -rawvideo w=352:h=288 foreman.yuv\n\n"); exit(EXIT_FAILURE); } int main(int argc, char **argv) { if(argc < 3 || argc > 3) { print_help(argc, argv); } FILE *fin = fopen(argv[1], "rb"); FILE *fout = fopen(argv[2], "wb"); if (!fin || !fout) { perror("fopen"); exit(EXIT_FAILURE); } struct c63_common *cm = calloc(1, sizeof(*cm)); cm->e_ctx.fp = fin; int framenum = 0; while(!feof(fin)) { printf("Decoding frame %d\n", framenum++); parse_c63_frame(cm); decode_c63_frame(cm, fout); } fclose(fin); fclose(fout); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <assert.h> #include <stdbool.h> #include <seq.h> #include <inttypes.h> #include <string.h> #define SIZE uint32_t /******************************/ /* */ /* ------------- */ /* | DECLARATIONS| */ /* ------------- */ /* */ /******************************/ /*******************************/ /* UM DATA Container */ /*******************************/ typedef struct UM_DATA_STRUCT { SIZE* zeroSeg; SIZE sizeZeroSeg; Seq_T segments; Seq_T unmappedSegs; SIZE pCounter; SIZE* registers; } *UM_data; /*******************************/ /* Initialize and Free */ /*******************************/ /* make_UM_data Inputs: none Returns: UM_data struct Does: allocates memory and inititalizes variables for the UM_data struct */ static inline UM_data make_UM_data(); /* initialize_UM_data Inputs: pointer to a file and UM_data struct Returns: none Does: intitializes the values in the struct by inputting a file into the seqs */ static inline void initialize_UM_data(FILE *fp, UM_data data); /* UM_data_free Inputs: Um_data struct pointer Returns: none Does: frees the struct */ static inline void UM_data_free(UM_data *data); /*******************************/ /* Getters */ /*******************************/ /* UM_data_get_pCounter Inputs: Um_data struct Returns: uint32_t Does: returns int program counter */ static inline SIZE UM_data_get_pCounter(UM_data data); /* UM_data_get_next_unmapped_loc Inputs: Um_data struct Returns: int Does: returns the next unmapped location in the segments array or -1 to addhi */ static inline SIZE UM_data_get_next_unmapped_loc(UM_data data); /* UM_data_get_segments_length Inputs: Um_data struct Returns: int Does: returns the lengths of the seq that holds all of the segments */ static inline SIZE UM_data_get_segments_length(UM_data data); /* UM_data_get_instruction Inputs: Um_data struct, uint32, uint32 Returns: uint32 Does: returns the instruction located at m[outer_i][inner_t] */ static inline SIZE UM_data_get_instruction(UM_data data, SIZE outer_i, SIZE inner_i); static inline SIZE UM_data_get_zeroSeg_instruction(UM_data data, SIZE inner_i); static inline SIZE* UM_data_makeTOarray(UM_data data); /* UM_data_get_seg_instruction_count Inputs: Um_data struct, int outer_u Returns: int Does: returns the number of instructions in a segment */ static inline SIZE UM_data_get_seg_instruction_count(UM_data data, SIZE outer_i); /* UM_data_get_regs Inputs: Um_data struct Returns: uint32_t pointer to the registers Does: returns the array of registers from the struct */ static inline SIZE* UM_data_get_regs(UM_data data); /*******************************/ /* Setters */ /*******************************/ /* UM_data_increment_pCounter Inputs: Um_data struct Returns: int Does: increments the program counter */ //extern int UM_data_increment_pCounter(UM_data data); /*UM_data_seg_put Inputs: Um_data struct, Seq_T, loc Returns:none Does: puts a segment on the sequence of segments in the location loc (or addhi) */ static inline void UM_data_seg_put(UM_data data, Seq_T new_seg, SIZE loc); /*UM_data_seg_addhi Inputs: Um_data struct, new_seg Returns: none Does: addhis a new segment on the seq of segments */ static inline void UM_data_seg_addhi(UM_data data, Seq_T new_seg); /*UM_data_set_instruction Inputs: Um_data struct, uint32, uint32, uint32 Returns: none Does: sets m[outer_i][inner_i] = val */ static inline void UM_data_set_instruction(UM_data data, SIZE outer_i, SIZE inner_i, SIZE val); /*UM_data_add_unmapped_loc Inputs: Um_data struct, uint32 Returns: none Does: adds a location to the unmapped segs seq */ static inline void UM_data_add_unmapped_loc(UM_data data, SIZE loc); /*UM_data_duplicate_and_set_seg Inputs: Um_data struct, uint32, uint32, Returns: none Does: copies a segment, sets it as the 0 segment and updates pCounter */ static inline void UM_data_duplicate_and_set_seg(UM_data data, SIZE outer_i, SIZE inner_i); /*******************************/ /* Static Declarations */ /* UM_ALU LOGIC */ /*******************************/ typedef uint32_t Um_instruction; typedef enum Um_opcode { CMOV = 0, SLOAD, SSTORE, ADD, MUL, DIV, NAND, HALT, ACTIVATE, INACTIVATE, OUT, IN, LOADP, LV } Um_opcode; typedef enum Um_register { r0 = 0, r1, r2, r3, r4, r5, r6, r7 } Um_register; static inline void UM_ALU_cMov(UM_data data, Um_register a, Um_register b, Um_register c); static inline void UM_ALU_SLoad(UM_data data, Um_register a, Um_register b, Um_register c); static inline void UM_ALU_SStore(UM_data data, Um_register a, Um_register b, Um_register c); static inline void UM_ALU_add(UM_data data, Um_register a, Um_register b, Um_register c); static inline void UM_ALU_multiply(UM_data data, Um_register a, Um_register b, Um_register c); static inline void UM_ALU_divide(UM_data data, Um_register a, Um_register b, Um_register c); static inline void UM_ALU_nand(UM_data data, Um_register a, Um_register b, Um_register c); static inline void UM_ALU_mapSeg(UM_data data, Um_register b, Um_register c); static inline void UM_ALU_unMapSeg(UM_data data, Um_register c); static inline void UM_ALU_output(UM_data data, Um_register c); static inline void UM_ALU_input(UM_data data, Um_register c); static inline void UM_ALU_loadP(UM_data data, Um_register b, Um_register c); static inline void UM_ALU_loadV(UM_data data, Um_register a, SIZE val); static inline int UM_ALU_Execute(Um_instruction word, UM_data data); /******************************/ /* */ /* ------------- */ /* | MAIN | */ /* ------------- */ /* */ /******************************/ int main(int argc, char const *argv[]) { /* VALIDATE INPUT */ if (argc != 2) { perror("Error - invalid input"); return EXIT_FAILURE; } /* check elements of file if file passes input check */ struct stat s; if (stat(argv[1], &s) == -1) { perror("Error - invalid file"); return EXIT_FAILURE; } else if ((s.st_size % 4) != 0) { perror("Error - incomplete file"); return EXIT_FAILURE; } FILE *program = fopen(argv[1], "rb"); UM_data data = make_UM_data(); initialize_UM_data(program, data); int go = 1; /*int go: == 0 --> error occured, exit EXIT_FAILURE == 1 --> all good, keep going == 2 --> halt instruction */ do{ Um_instruction instruction = UM_data_get_zeroSeg_instruction( data, UM_data_get_pCounter(data)); go = UM_ALU_Execute(instruction, data); } while (go == 1); if (go == 0) { UM_data_free(&data); fclose(program); return EXIT_FAILURE; } UM_data_free(&data); fclose(program); return EXIT_SUCCESS; } /******************************/ /* */ /* ---------------- */ /* | IMPLEMENTATIONS| */ /* ---------------- */ /* */ /******************************/ static inline int UM_data_increment_pCounter(UM_data data) { SIZE full = ~0; if (data->pCounter == full) { return 0; } else if (data->pCounter == data->sizeZeroSeg) { return 0; } else { data->pCounter += 1; } return 1; } /* IMPLEMENTATION OF BITPACK COPIED FROM SUPPLIED BITPACK.c */ static inline uint64_t shl(uint64_t word, unsigned bits) { if (bits == 64) return 0; else return word << bits; } /* * shift R logical */ static inline uint64_t shr(uint64_t word, unsigned bits) { if (bits == 64) return 0; else return word >> bits; } /* * shift R arith */ static inline int64_t sra(uint64_t word, unsigned bits) { if (bits == 64) bits = 63; /* will get all copies of sign bit, * which is correct for 64 */ /* Warning: following uses non-portable >> on signed value...see K&R 2nd edition page 206. */ return ((int64_t) word) >> bits; } static inline uint64_t Bitpack_getu(uint64_t word, unsigned width, unsigned lsb) { unsigned hi = lsb + width; /* one beyond the most significant bit */ /* different type of right shift */ return shr(shl(word, 64 - hi), 64 - width); } /****************************************************************/ static inline bool Bitpack_fitsu(uint64_t n, unsigned width) { if (width >= 64) return true; /* thanks to Jai Karve and John Bryan */ /* clever shortcut instead of 2 shifts */ return shr(n, width) == 0; } /****************************************************************/ static inline uint64_t Bitpack_newu(uint64_t word, unsigned width, unsigned lsb, uint64_t value) { unsigned hi = lsb + width; /* one beyond the most significant bit */ return shl(shr(word, hi), hi) /* high part */ | shr(shl(word, 64 - lsb), 64 - lsb) /* low part */ | (value << lsb); /* new part */ } /*******************************/ /* MAIN ALU UNIT IMPLEMENTATION*/ /*******************************/ static inline int UM_ALU_Execute(Um_instruction word, UM_data data) { Um_register regC, regB, regA; int val; int opcode = Bitpack_getu(word, 4, 28); int go = 0; if (opcode != LV){ regC = Bitpack_getu(word, 3, 0); regB = Bitpack_getu(word, 3, 3); regA = Bitpack_getu(word, 3, 6); } else { val = Bitpack_getu(word, 25, 0); regA = Bitpack_getu(word, 3, 25); UM_ALU_loadV(data, regA, val); return UM_data_increment_pCounter(data); } switch (opcode) { case CMOV /* Conditional Move */: UM_ALU_cMov(data, regA, regB, regC); go = UM_data_increment_pCounter(data); break; case SLOAD /* Segmented Load */: UM_ALU_SLoad(data, regA, regB, regC); go = UM_data_increment_pCounter(data); break; case SSTORE /* Segmented Store */: UM_ALU_SStore(data, regA, regB, regC); go = UM_data_increment_pCounter(data); break; case ADD /* ADD */: UM_ALU_add(data, regA, regB, regC); go = UM_data_increment_pCounter(data); break; case MUL /* MULTIPLY */: UM_ALU_multiply(data, regA, regB, regC); go = UM_data_increment_pCounter(data); break; case DIV /* DIVIDE */: UM_ALU_divide(data, regA, regB, regC); go = UM_data_increment_pCounter(data); break; case NAND /* NAND */: UM_ALU_nand(data, regA, regB, regC); go = UM_data_increment_pCounter(data); break; case HALT /* HALT */: return 2; case ACTIVATE /* MAP SEGMENT */: UM_ALU_mapSeg(data, regB, regC); go = UM_data_increment_pCounter(data); break; case INACTIVATE /* UNMAP SEGMENT */: UM_ALU_unMapSeg(data, regC); go = UM_data_increment_pCounter(data); break; case OUT /* OUTPUT */: UM_ALU_output(data, regC); go = UM_data_increment_pCounter(data); break; case IN /* INPUT */: UM_ALU_input(data, regC); go = UM_data_increment_pCounter(data); break; case LOADP /* Load Program */: UM_ALU_loadP(data, regB, regC); return 1; default /* FAILURE */: return 0; } return go; } /*******************************/ /* Static ALU Implementations */ /*******************************/ static inline void UM_ALU_cMov(UM_data data, Um_register a, Um_register b, Um_register c) { SIZE *r = UM_data_get_regs(data); if (r[c] != 0){ r[a] = r[b]; } } static inline void UM_ALU_SLoad(UM_data data, Um_register a, Um_register b, Um_register c) { SIZE *r = UM_data_get_regs(data); if (r[b] == 0) { r[a] = UM_data_get_zeroSeg_instruction(data, r[c]); } else { r[a] = UM_data_get_instruction(data, r[b], r[c]); } } static inline void UM_ALU_SStore(UM_data data, Um_register a, Um_register b, Um_register c) { SIZE *r = UM_data_get_regs(data); UM_data_set_instruction(data, r[a], r[b], r[c]); } static inline void UM_ALU_add(UM_data data, Um_register a, Um_register b, Um_register c) { /* 2 << 31 == 2^32 ... mod addition by 2^32*/ SIZE *r = UM_data_get_regs(data); r[a] = ((r[b] + r[c]) % ((uint64_t)2 << 31)); } static inline void UM_ALU_multiply(UM_data data, Um_register a, Um_register b, Um_register c) { SIZE *r = UM_data_get_regs(data); r[a] = ((r[b] * r[c]) % ((uint64_t)2 << 31)); } static inline void UM_ALU_divide(UM_data data, Um_register a, Um_register b, Um_register c) { SIZE *r = UM_data_get_regs(data); r[a] = (r[b] / r[c]); } static inline void UM_ALU_nand(UM_data data, Um_register a, Um_register b, Um_register c) { SIZE *r = UM_data_get_regs(data); r[a] = ~(r[b] & r[c]); } static inline void UM_ALU_mapSeg(UM_data data, Um_register b, Um_register c) { SIZE *r = UM_data_get_regs(data); Seq_T new_seg = Seq_new(0); /*initialize r[c] number of spaces*/ for (SIZE i = 0; i < r[c]; i++){ Seq_addlo(new_seg, 0); } SIZE loc = UM_data_get_next_unmapped_loc(data); SIZE full = ~0; /*above func returns all ones if seq is empty if seq isnt empty add at loc, else addhi */ if (loc != full && loc != 0) { UM_data_seg_put(data, new_seg, loc); r[b] = loc; } else { UM_data_seg_addhi(data, new_seg); r[b] = UM_data_get_segments_length(data) - 1; } } static inline void UM_ALU_unMapSeg(UM_data data, Um_register c) { SIZE *r = UM_data_get_regs(data); UM_data_add_unmapped_loc(data, r[c]); } static inline void UM_ALU_output(UM_data data, Um_register c) { SIZE *r = UM_data_get_regs(data); assert(r[c] < 256); fprintf(stdout, "%c", r[c]); } static inline void UM_ALU_input(UM_data data, Um_register c) { int in = fgetc(stdin); SIZE *r = UM_data_get_regs(data); if (in == EOF) { r[c] = ~0; } else{ assert(in < 256); r[c] = in; } } static inline void UM_ALU_loadP(UM_data data, Um_register b, Um_register c) { SIZE *r = UM_data_get_regs(data); UM_data_duplicate_and_set_seg(data, r[b], r[c]); } static inline void UM_ALU_loadV(UM_data data, Um_register a, SIZE val) { SIZE *r = UM_data_get_regs(data); r[a] = val; } /*******************************/ /* Initialize and Free */ /*******************************/ /* make_registerArray Inputs: none Returns: SIZE pointer Does: makes a register array that is used for the data struct */ static inline SIZE* make_registerArray() { SIZE* array = malloc(32); for (int i = 0; i < 7; i++) { array[i] = 0; } return array; } static inline UM_data make_UM_data() { UM_data UM = malloc(sizeof(struct UM_DATA_STRUCT)); UM->zeroSeg = NULL; UM->segments = Seq_new(0); UM->unmappedSegs = Seq_new(0); UM->registers = make_registerArray(); UM->pCounter = 0; return UM; } static inline void initialize_UM_data(FILE *fp, UM_data data) { int count = 0; int byte; int i = 0; SIZE instruction = 0; Seq_T zero_seg = Seq_new(0); while (EOF != (byte = fgetc(fp))) { instruction = Bitpack_newu(instruction, 8, 8*(3-count), byte); if (count == 3) { Seq_addhi(zero_seg, (void*)(uintptr_t)instruction); instruction = 0; count = 0; i++; } else { count++; } } data->sizeZeroSeg = i-1; Seq_addlo(data->segments, (void*)zero_seg); data->zeroSeg = UM_data_makeTOarray(data); data->pCounter = 0; } static inline void UM_data_free(UM_data *data) { for (int i = 0; i < Seq_length((*data)->segments); i++) { Seq_T innerSeg = Seq_get((*data)->segments, i); Seq_free(&innerSeg); } free((*data)->zeroSeg); Seq_free(&((*data)->segments)); Seq_free(&((*data)->unmappedSegs)); free(((*data)->registers)); free(*data); } static inline SIZE* UM_data_makeTOarray(UM_data data) { int numVals = UM_data_get_seg_instruction_count(data, 0); Seq_T targetSeg = Seq_get(data->segments, 0); if (data->zeroSeg != NULL) { free(data->zeroSeg); } //fprintf(stderr, "%s", "NULL"); SIZE* zero_seg = malloc(sizeof(SIZE) * numVals); for (int i = 0; i < numVals; i++) { zero_seg[i] = ((SIZE)(uintptr_t)Seq_get(targetSeg, i)); } return zero_seg; } /*******************************/ /* Getters */ /*******************************/ static inline SIZE UM_data_get_pCounter(UM_data data) { return data->pCounter; } static inline SIZE* UM_data_get_regs(UM_data data) { return data->registers; } static inline SIZE UM_data_get_segments_length(UM_data data) { return Seq_length(data->segments); } static inline SIZE UM_data_get_instruction(UM_data data, SIZE outer_i, SIZE inner_i) { Seq_T segment = Seq_get(data->segments, outer_i); void* instruction = Seq_get(segment, inner_i); return ((SIZE)(uintptr_t)instruction); } static inline SIZE UM_data_get_zeroSeg_instruction(UM_data data, SIZE inner_i) { return (data->zeroSeg)[inner_i]; } static inline SIZE UM_data_get_seg_instruction_count(UM_data data, SIZE outer_i) { Seq_T inner_seg = Seq_get(data->segments, outer_i); return Seq_length(inner_seg); } static inline SIZE UM_data_get_next_unmapped_loc(UM_data data) { if (Seq_length(data->unmappedSegs) != 0){ void* val = Seq_remlo(data->unmappedSegs); return (SIZE)(uintptr_t)val; } return ~0; } /*******************************/ /* Setters */ /*******************************/ /*put a segment on segments*/ static inline void UM_data_seg_put(UM_data data, Seq_T new_seg, SIZE loc) { if (loc < (unsigned)Seq_length(data->segments)) { Seq_put(data->segments, loc, (void*)new_seg); } else { UM_data_seg_addhi(data, (void*)new_seg); } } static inline void UM_data_seg_addhi(UM_data data, Seq_T new_seg) { Seq_addhi(data->segments, (void*)new_seg); } static inline void UM_data_duplicate_and_set_seg(UM_data data, SIZE outer_i, SIZE inner_i) { //printf("in dands"); if (outer_i != 0) { data->sizeZeroSeg = UM_data_get_seg_instruction_count(data, outer_i); Seq_T new_seg = Seq_new(data->sizeZeroSeg); for (SIZE i = 0; i < data->sizeZeroSeg; i++) { Seq_addhi(new_seg, (void*)(uintptr_t) UM_data_get_instruction(data, outer_i, i)); } Seq_put(data->segments, 0 , new_seg); free(data->zeroSeg); data->zeroSeg = NULL; data->zeroSeg = UM_data_makeTOarray(data); } data->pCounter = inner_i; } static inline void UM_data_set_instruction(UM_data data, SIZE outer_i, SIZE inner_i, SIZE val) { if (outer_i == 0) { (data->zeroSeg)[inner_i] = val; } Seq_T segment = Seq_get(data->segments, outer_i); Seq_put(segment, inner_i, (void*)(uintptr_t)val); } static inline void UM_data_add_unmapped_loc(UM_data data, SIZE loc) { Seq_addhi(data->unmappedSegs, (void*)(uintptr_t)loc); } #undef WORD
C
#include <stdio.h> #include <stdlib.h> #include "stack.h" #include "dmanager.h" struct Node* stack[MAX_STACK_ELEMS]; int position = 0; struct Node* functions[MAX_FUNCTIONS]; int p_functions = 0; void add(struct Node* node){ stack[position] = node; position++; } struct Node* pop(){ position--; return stack[position]; } int get_tot_stack(){ return position; } void add_function_stack(struct Node* node){ functions[p_functions] = node; p_functions++; } struct Node* pop_function_stack(){ p_functions--; return functions[p_functions]; } int get_tot_functions(){ return p_functions; }
C
/* ======================================== * * Copyright YOUR COMPANY, THE YEAR * All Rights Reserved * UNPUBLISHED, LICENSED SOFTWARE. * * CONFIDENTIAL AND PROPRIETARY INFORMATION * WHICH IS THE PROPERTY OF your company. * * ======================================== */ #include "InterruptRoutines.h" #include "project.h" #include "settings.h" #define stop 0b00 #define ch0 0b01 #define ch1 0b10 #define both 0b11 #define max_samples 15 //having 4 r/w bits in the CONTROL REGISTER 0 to specify the number of samples (within 50Hz to average) these may vary between 1 and 15 #define clk_freq 100000 //Hz this is the frequency of the timer's clock #define comm_freq 50 //Hz this is the frequency at which the samples' average must be communicated (updated) extern uint8_t slaveBuffer[]; //contains the slave's registers: CONTROL REGISTER 0, CONTROL REGISTER 1, MSB and LSB of channel 0 and MSB and LSB of channel 1 (notice: this is the correct order to communicate 16 bit values by I2C) int flag_ch0, flag_ch1, Nsample, flag_ch0_temp, flag_ch1_temp; extern int32 value_digit[max_samples*2]; //with 4 bits to do so 15 samples to averge may be desired at most, since it is for 2 sensors 30 int8 count=-1; //increased at each ISR and reset to -1 (and immediately increased to 0) only when a cycle (update of slave buffer's averaged samples registes) is comlete int32 period; /*to be performed at each timer's overflow (timer's period is set as required by the user-configurable parameters)*/ CY_ISR(Custom_Timer_Count_ISR) { //Read timer status register to pull interrupt line low Timer_ADC_ReadStatusRegister(); /*for robustess the user must wait for a cycle to finish before the required modifications to Nsamples or the status bits take action*/ if (count==-1) { Nsample = (slaveBuffer[0] >> 2) & 0b1111; //default is 5: 0101 /*it makes no sense to average 0 samples any input to the bridge control panel's write between 00 and 03 is corrected to give the same output as 04 to 07 respectively*/ /*notice no value above 3f may be given in input to the bridge control manel since the 2 status bits may be 0b11 at most and the 4 ones for the number of samples 0b1111 (15 in dec), this makes 0b111111 which corresponds to 3f in hex*/ if (Nsample==0) Nsample=1; if (slaveBuffer[1]==0) slaveBuffer[1]=1;//if the user requests a frequency of communication (value update) of 0Hz it is automatically corrected to 1 Hz flag_ch0_temp=flag_ch0; flag_ch1_temp=flag_ch1; /* set the timer's period according to the number of samples to average each 50Hz per channel*/ Timer_ADC_Stop(); //stop the timer to reset the period period= clk_freq/(slaveBuffer[1]*2*Nsample); //sampling is done at each timer's overflow so its period is set thus //period changes when the counter is reloded so we are sure the timer counts from 0 to overflow Timer_ADC_WritePeriod(period); //done following ISR's (calls function settings) interrogation of what is written in the Bridge Control Panel Timer_ADC_Enable(); //reactivates timer once period is changed } count++; /*this function takes in input the status: which channels to sample, and how many samples to average and writes the registers of the slave buffer with the avg sample values and sets the timer and the ADC in order to satisfy the requirements set by these parameters */ settings(flag_ch0_temp, flag_ch1_temp, Nsample); } void EZI2C_ISR_ExitCallback(void) //to be performed upon command from the bridge control panel { //check the contence og the least significant bits of the CONTROL REGISTER 0 (channels to sample) switch (slaveBuffer[0] & 0b11){ case stop: //LED off and stop sampling Pin_LED_Write(0); flag_ch0=0; flag_ch1=0; break; case ch0: //LED off and sample only ch 0 (Temperature sensor) Pin_LED_Write(0); flag_ch0=1; flag_ch1=0; break; //LED off and sample only ch 1 (LDR) case ch1: Pin_LED_Write(0); flag_ch0=0; flag_ch1=1; break; case both: //LED on and sample both channels Pin_LED_Write(1); flag_ch0=1; flag_ch1=1; break; } } /* [] END OF FILE */
C
#include <cavan.h> #include <cavan/progress.h> static void progress_bar_fflush(struct progress_bar *bar) { print_ntext((char *) &bar->body, sizeof(struct progress_bar_body)); print_char('\r'); } static int update_percent(struct progress_bar *bar) { int percent = (int) (((double) bar->current) * 100 / bar->total); if (percent == bar->percent) { return 0; } bar->percent = percent; sprintf(bar->body.percent, " %d%%", percent); bar->body.percent[5] = ' '; return 1; } static void fill_buffer(char *content, int fill, int size) { char *end = content + size; while (content < end) { if (fill > 0) { *content = FULL_CHAR; fill--; } else { *content = FREE_CHAR; } content++; } } static int update_content(struct progress_bar *bar) { int length; length = (int) (((double) bar->current) * HALF_LENGTH * 2 / bar->total); if (length == bar->length) { return 0; } bar->length = length; if (length <= HALF_LENGTH) { fill_buffer(bar->body.content1, length, HALF_LENGTH); memset(bar->body.content2, FREE_CHAR, HALF_LENGTH); } else { memset(bar->body.content1, FULL_CHAR, HALF_LENGTH); fill_buffer(bar->body.content2, length - HALF_LENGTH, HALF_LENGTH); } return 1; } void progress_bar_update(struct progress_bar *bar) { if (bar->current > bar->total) { return; } if (update_percent(bar) | update_content(bar)) { progress_bar_fflush(bar); } } void progress_bar_init(struct progress_bar *bar, u64 total) { struct progress_bar_body *body = &bar->body; bar->total = total == 0 ? 1 : total; bar->current = 0; bar->percent = -1; bar->length = -1; body->head = '['; memset(body->percent, 0, sizeof(body->percent)); body->tail = ']'; progress_bar_update(bar); } void progress_bar_add(struct progress_bar *bar, u64 val) { bar->current += val; progress_bar_update(bar); } void progress_bar_set(struct progress_bar *bar, u64 val) { bar->current = val; progress_bar_update(bar); } void progress_bar_finish(struct progress_bar *bar) { bar->current = bar->total; progress_bar_update(bar); print_char('\n'); }
C
#include <jansson.h> #include <string.h> // Read Cosm config file for Ip, port, and api ke CosmConfig *readCosmConfig() { int url_length; int api_key_length; char URL_CHAR[128]; char API_KEY_CHAR[128]; // JSON nodes json_t *root, *url, *json_feed, *api_key; json_error_t error; // Read the JSON contents root = json_load_file("Cosm/config.json", 0, &error); if(!root) { CosmError("\nError when parsing Cosm Config File"); } // Get url, Feed, and API_KEY url = json_object_get(root, "URL"); json_feed = json_object_get(root, "feed"); api_key = json_object_get(root, "API_KEY"); // Get values strcpy(URL_CHAR, json_string_value(url)); strcpy(API_KEY_CHAR, json_string_value(api_key)); // Free json objects free(root); free(url); free(api_key); // Allocate memory for config CosmConfig *config = malloc(sizeof(CosmConfig *)); url_length = strlen(URL_CHAR); api_key_length = strlen(API_KEY_CHAR); // url length + 1 for NULL config->Url = (char *) malloc(url_length + 1); // API key length + 1 for NULL config->Api_key = (char *) malloc(api_key_length + 1); if(!config->Url || !config->Api_key) { CosmError("Can't allocate memory for Cosm Configuration"); } strcpy(config->Url, URL_CHAR); strcpy(config->Api_key, API_KEY_CHAR); config->Feed = json_integer_value(json_feed); return config; }
C
// NEO01 #include <stdio.h> #define ll long long #define gc getchar_unlocked #define INF 1000000000000000000LL int getn(){ int n = 0, c = gc(), f = 1; while(c != '-' && (c < '0' || c > '9')) c = gc(); if(c == '-') f = -1, c = gc(); while(c >= '0' && c <= '9') n = (n<<3) + (n<<1) + c - '0', c = gc(); return n * f; } void sort(int* a, int n){ if(n < 2) return; int p = a[n>>1], *l = a, *r = a+n-1, t; while(l <= r){ if(*l < p){ l++; continue; } if(*r > p){ r--; continue; } t = *l; *l++ = *r; *r-- = t; } sort(a, r-a+1); sort(l, a+n-l); } int a[100000]; int main(){ int T,N, i,k,n; ll m,r,s; T = getn(); while(T--){ N = getn(); for(r = s = n = i = 0; i < N; ++i) a[i] = getn(); sort(a, N); m = -INF, s = n = 0; for(i = N-1; i >= 0; --i){ s += a[i], ++n; if(s*n > m) m = s*n, k = i; } r = m; for(i = k-1; i >= 0; --i) r += a[i]; printf("%lld\n", r); } return 0; }
C
#include "dijkstra.h" /*function that ties the whole algorithm together and runs it in the correct fashion, returning the results required. Goes a little beyond the general implementation of Dijkstra's algorithm and does the results checking to find the cheapest, viable location to travel, as well as backtracking to determine the predecessors. Finally, it returns what it found in a results_t struct defined above.*/ results_t dijkstra(place_t places[],int** costs, int num_places, preference_t preference) { priority_queue *pq; int dist[num_places+1]; int pred[num_places +1]; int source_index=-1; int i,j; q_element s[num_places]; q_element temp; void *tmp; /*temp pointer for testing malloc */ results_t result; /*initialise in case no match */ result.place_ID=NO_MATCH; result.min_cost=INT_MAX; result.num_preds=0; /*work out the index of the requested city */ /*confirmed working, case sensitively of course. */ for(i=0;i<num_places;i++){ if (strcmp(preference.source,places[i+1].city)==0) { source_index=i+1; break; } } /*initialise a priority queue which stores the index of the city, and is maintained in a heap, weighted on the cost from the source node*/ /*test all mallocs to ensure they don't fail */ tmp=malloc(sizeof(q_element)*num_places+sizeof(int)+ sizeof(int)*num_places); if (!tmp) { printf("Failed to allocate memory \n"); exit(EXIT_FAILURE); } pq=tmp; tmp=malloc(sizeof(q_element)*num_places); if (!tmp) { printf("Failed to allocate memory \n"); exit(EXIT_FAILURE); } pq->q=tmp; tmp=malloc(sizeof(int)*num_places); if (!tmp) { printf("Failed to allocate memory \n"); exit(EXIT_FAILURE); } pq->hash=tmp; /*initialise the data to be stored in the pq */ for(i=0;i<num_places;i++) { temp.ID=i+1; /*initialise with costs from source */ temp.cost=costs[source_index][i+1]; s[i]=temp; } /*make sure the source gets pulled off the queue first. */ s[source_index-1].cost=0; /*constructs heap using the data made above */ make_heap(pq,s,num_places); /*check heap got made okay */ if (DEBUG) { for(i=0;i<num_places;i++){ printf("Min cost from city index %d is %d\n" ,pq->q[i+1].ID,pq->q[i+1].cost); } } if (DEBUG) { printf("source index is %d\n",source_index); /*sees if it read the costs correctly */ for(i=0;i<num_places;i++) { for(j=0;j<num_places;j++) { printf("The cost from %s to %s is %d\n", places[i+1].city,places[j+1].city, costs[i+1][j+1]); } } } /*initialise the dist,pred arrays */ initialize(dist,pred,num_places+1,source_index); /*runs dijkstra's algorithm */ run(pq,dist,pred,costs,source_index,preference,places,num_places); /*check if predecessor's were correctly determined*/ if(DEBUG){ for(i=0;i<=num_places;i++) { printf("The predecessor for %d is %d\n",i,pred[i]); } } /*okay, pred and dist arrays made, process results */ result=results_processor(places,dist,preference,pred,num_places); return result; } /*function to initialise the distance and pred arrays */ void initialize(int dist[],int pred[],int num_vertices, int source) { int i; /*all costs except that to the source are initialised to INT_MAX*/ for(i=0;i<=num_vertices;i++) dist[i] = INT_MAX; dist[source]=0; for(i=0;i<=num_vertices;i++) pred[i]=NO_PRED; } /*function that actually runs the important parts of dijkstra's algorithm */ void run(priority_queue *pq,int dist[],int pred[],int** costs, int source_index, preference_t preferences, place_t places[], int num_places){ int i; /* counter */ q_element temp; /*storage for what get's dequeued */ /*keep going while queue isn't empty */ while(pq->n>0) { /*take the root off the priority queue */ temp=extract_min(pq); dist[temp.ID]=temp.cost; if(DEBUG){ printf("Dist from source with identity %d is: %d \n",temp.ID , temp.cost); } for (i=0;i<num_places;i++) { /*safeguard from integer overflow */ if(costs[temp.ID][i+1]!=INT_MAX){ /*only updates if it will decrease the distance */ if(dist[temp.ID]+costs[temp.ID][i+1] <dist[i+1]) { /*calls update to ensure the priority queue has the correct values and maintains the heap property */ update(i+1,temp.ID,pred,dist,pq,costs); } } } } /*okay dist/pred arrays populated */ /*let's check out what we got, distance wise */ if (DEBUG) { for(i=1;i<=num_places;i++) { printf("The min cost from %s to %s is: %d\n", places[source_index].city, places[i].city, dist[i]); } } } /*function to check whether a particular place fulfills what the user requested/inputed. Returns 1 if the place is a match, 0 if it isn't. */ int check_match(int id, place_t places[], preference_t preferences) { /*have to compare a few things*/ /*only bother checking continent is okay if it isn't 'any' */ if (strcmp(preferences.continent,"any")) { if (strcmp(places[id].continent,preferences.continent)!=0) return 0; } /*Only important to check if the preference matches the place if the user selected yes to cultural/outdoors interest required */ if (strcmp(preferences.cultural,"Y")==0) { if (strcmp(places[id].cultural,"Y")!=0) return 0; } if (strcmp(preferences.outdoors,"Y")==0) { if (strcmp(places[id].outdoors,"Y")!=0) return 0; } /*it's a match! */ return 1; } /*function to update the dist, pred arrays, as well as ensure the priority queue is up to scratch */ void update(int v,int current,int pred[], int dist[], priority_queue *pq, int **costs) { /*update dist/pred arrays */ dist[v]=dist[current]+costs[current][v]; pred[v]=current; /*update the priority queue in the right position, using its built in hash table to ensure the correct index gets updated. This newly updated node is then bubbled up to ensure the heap property is maintained */ decrease_priority(pq,pq->hash[v],dist[v]); if (DEBUG) printf("The new distance to %d is: %d through %d \n", v,dist[v],pred[v]); } /*function for processing the results. finds the cheapest place (which fulfills the user inputted criteria) (if there is one), then backtracks the predecessors (if there are any), returning all this in a proprietry struct fit for this purpose. beyond the scope of dijkstra's algorithm */ results_t results_processor(place_t places[],int dist[],preference_t preference, int pred[], int num_places) { results_t result; /*storage for to-be determined results */ /*initialise in case no match */ result.place_ID=NO_MATCH; result.min_cost=INT_MAX; result.num_preds=0; int i; /*process results to see if there was a match, and if so, to find the cheapest such match */ for (i=0;i<num_places;i++) { /*make sure not to include source by not allowing the distance to be zero*/ /*keep track of which place can be reached at the lowest cost, given it fulfills the user preferences */ if(dist[i+1] < result.min_cost && dist[i+1]>0) { if(check_match(i+1,places,preference)){ result.place_ID=i+1; result.min_cost=dist[i+1]; } } } /*don't bother finding preds if no optimum place */ if(result.place_ID==NO_MATCH) { /*algorithm's finished, return results (didn't find a suitable place */ return result; } /*find preds*/ i=result.place_ID; /*not quite worth re-allocating every time you have a new predecessor, so just allocate enough room for the maximal number of predecessor. This isn't such a big deal because it is just a simple array of ints which won't use up any significant amount of memory on any modern computer */ result.preds=malloc(sizeof(int)*num_places); /*make sure malloc didn't fail */ if(!result.preds) { printf("Failed to allocate memory \n"); exit(EXIT_FAILURE); } /*keep track of how many predecessors there are */ result.num_preds=0; /*keep going until we arrive back to the source */ while(pred[i]!=-1){ result.preds[result.num_preds]=pred[i]; i=pred[i]; result.num_preds++; } /*ensures the number of predecessors is returned alongside the other data such as the destination, the minimum cost, and the identities of all the predecessors */ return result; }
C
#include <stdio.h> #include <malloc.h> #define MAXQSIZE 100 //最大值 #define MAX_VERTEX_NUM 20 //最大顶点数 #define INFINITY 10000000 //最大值 #define OK 1 int visited[MAX_VERTEX_NUM];//访问标志数组 typedef struct ArcCell // 弧的定义 { int adj; // 用1或0表示是否相邻 } AdjMatrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; typedef struct// 图的定义 { AdjMatrix arcs; // 弧的信息 int vexnum, arcnum; // 顶点数,弧数 } Graph; typedef struct QNode { int data; struct QNode *priou; struct QNode *next; }QNode, LinkList, *QueuePtr; typedef struct { QueuePtr front; QueuePtr rear; }LinkQueue; //队列基本操作 int InitQueue(LinkQueue *Q)//初始化队列 { Q->front = Q->rear = (QueuePtr)malloc(MAXQSIZE * sizeof(QNode));//分配队列空间 if (!(Q->front)) { return 0; } Q->front->next = Q->rear->next = NULL; return OK; } int EnQueue(LinkQueue *Q, int e)//入队列 { QueuePtr p; p = (QueuePtr)malloc(sizeof(QNode)); if (!p) { return 0; } p->data = e; p->next = NULL; p->priou = Q->front; Q->rear->next = p; Q->rear = p; return OK; } int QueueEmpty(LinkQueue Q)//判断队列是否为空 { if (Q.front == Q.rear) { return 1; } return 0; }; int DeQueue(LinkQueue *Q, int *e)//出队列 { if (QueueEmpty(*Q)) //队列为空 { return 0; } Q->front = Q->front->next; *e = Q->front->data; return OK; } //图的操作 int FirstAdjVex(Graph G, int i)//返回第一个邻接顶点,若无则返回-1 { int k; for (k = 0; k < G.vexnum; k++) { if (G.arcs[i][k].adj == 1) { return k; } } return -1; } int NextAdjVex(Graph G, int i, int j)//返回下一个邻接顶点,若无则返回-1 { int k; for (k = j + 1; k < G.vexnum; k++) { if (G.arcs[i][k].adj == 1) { return k; } } return -1; } int Add(Graph*G, int x, int y) ////构造邻接矩阵并赋值 { if (x >= MAX_VERTEX_NUM || y >= MAX_VERTEX_NUM) { return 0; } G->arcs[x][y].adj = G->arcs[y][x].adj = 1;//相邻则赋值为1 return OK; } int CreateGraph(Graph *G) //构建已知图 { int i, j; G->vexnum = 9; //顶点 G->arcnum = 12; //边 for (i = 0; i < G->vexnum; i++) { for (j = 0; j < G->vexnum; j++) { G->arcs[i][j].adj = INFINITY; //初始化邻接矩阵,INFINITY表示不相邻 } } //初始化图,相邻顶点赋值 Add(G, 0, 1); Add(G, 0, 2); Add(G, 0, 3); Add(G, 0, 6); Add(G, 1, 2); Add(G, 3, 4); Add(G, 3, 5); Add(G, 4, 5); Add(G, 5, 7); Add(G, 6, 7); Add(G, 6, 8); Add(G, 7, 8); return OK; } void PrintFoot(LinkQueue Q, int start)//输出顶点间最短路径 { int i; int foot[MAX_VERTEX_NUM]; QueuePtr p; p = Q.rear; for (i = 0; i < MAX_VERTEX_NUM; i++) { foot[i] = -1; } foot[0] = p->data; p = p->priou; for (i = 1; p->data != start; i++) { foot[i] = p->data; p = p->priou; } foot[i] = p->data; for (; i >= 0; i--) //倒序输出 { if (foot[i] >= 0) { printf("%d ", foot[i] + 1); } } } void BFSTraverse(Graph G, int a, int b) //广度优先遍历 { LinkQueue Q; //辅助队列Q int i = 0; int flag = 0; for (int j = 0; j < G.vexnum; ++j) { visited[j] = 0; //初始化访问标志 } InitQueue(&Q); // 初始化辅助队列Q EnQueue(&Q, a); //起点入队列 visited[a] = 1; while (!QueueEmpty(Q)) //队列不为空 { DeQueue(&Q, &i); for (int k = FirstAdjVex(G, i); k >= 0; k = NextAdjVex(G, i, k))//相邻顶点入队列 { if (k == b) { EnQueue(&Q, k); PrintFoot(Q, a); //输出顶点间最短路径 flag = 1; break; } if (!visited[k]) { EnQueue(&Q, k); visited[k] = 1; } } if (flag == 1) { break; } } } void main() { int i, j; Graph G; CreateGraph(&G); printf("各顶点间最短路径依次为:\n\n"); for (i = 0; i < 9; i++) { for (j = 0; j < 9; j++) { if (j != i) { printf("%d<->%d:", i + 1, j + 1); BFSTraverse(G, i, j); printf("\n"); } } } }
C
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<pthread.h> pthread_mutex_t my_lock; int g_var; void * pthread1(void * arg) { printf("ENTER pthread1!\n"); pthread_mutex_lock(&my_lock); for(int i = 0; i<10; i++) { //pthread_mutex_lock(&my_lock); g_var++; printf("th1:%d\n", g_var); //pthread_mutex_unlock(&my_lock); sleep(1); } pthread_mutex_unlock(&my_lock); return NULL; } void * pthread2(void * arg) { printf("ENTER pthread2!\n"); //printf("trylock:%d\n",pthread_mutex_trylock(&my_lock)); while(pthread_mutex_trylock(&my_lock)) { printf("pthread2 wait!\n"); sleep(1); } for(int i = 0; i<10; i++) { //pthread_mutex_lock(&my_lock); g_var--; printf("th2:%d\n", g_var); //pthread_mutex_unlock(&my_lock); sleep(1); } pthread_mutex_unlock(&my_lock); return NULL; } int main() { pthread_t tid1,tid2; pthread_mutex_init(&my_lock, NULL); pthread_create(&tid1, NULL, pthread1, NULL); pthread_create(&tid2, NULL, pthread2, NULL); pthread_join(tid1, NULL); pthread_join(tid2, NULL); return 0; }
C
/* * p1316.c * * Created on: Mar 17, 2010 * Author: XTOg */ #include <stdio.h> int main(int argc, char* argv[]) { int MAX = 10000; int self[MAX + 1]; int i, j, sum; for (i = 1; i <= MAX; ++i) { self[i] = 1; } for (i = 1; i < MAX; ++i) { sum = i; for (j = i; j; j /= 10) { sum += j % 10; } if (sum <= MAX) { self[sum] = 0; } } for (i = 1; i <= MAX; ++i) { if (self[i]) { printf("%d\n", i); } } return 0; }
C
/* Exercise 4: Using a while loop enter in 8 numbers from the keyboard */ /* Calculate the sum of all numbers entered /* Joe O'Regan */ /* 30-09-2015 */ #include<stdio.h> main() { int i=1; int sum=0; int input; printf("Adding 5 numbers entered\n"); while(i<=5) { printf("Enter number: "); scanf("%d",&input); i++; // data is not stored, overwritten sum+=input; } printf("The sum of the numbers is %d", sum); getch(); return(0); }
C
// // UserInput.c // WritingSkills // // Created by Aleksandra Korolczuk on 2017-09-05. // Copyright © 2017 Aleksandra Korolczuk. All rights reserved. // #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <ctype.h> #include "UserInput.h" #include "Result.h" #include "Instructions.h" #define true 1 #define false 0 char input[100] = ""; int option_number = 0; int examOptions(){ int exam = 0; printf("---------------------MENU--------------------------\n"); printf("What exam are you taking?\n"); printf("Type numbers only.\n"); printf("1 - CELPIP\n"); printf("2 - IELTS\n"); printf("9 - QUIT\n"); option_number = checkInput(); while(option_number == false){ checkInput(); } if (option_number == 1) { printf("Your choice is Celpip.\n"); exam = 1; } else if (option_number == 2) { printf("Please choose if you are writing task 1 for 150 words (press 1) or task 2 for 250 words(press 2).\n"); int task = checkInput(); if (task == 1){ printf("Your choice is IELTS, task 1 for 150 words.\n"); exam = 2; }else if(task == 2) { printf("Your choice is IELTS, task 2 for 250 words.\n"); exam = 3; } } return exam; } int startWriting(int option){ printf("---------------------MENU--------------------------\n"); printf("1 - START WRITING\n"); printf("2 - GO BACK TO EXAM OPTIONS\n"); printf("# - SUBMIT THE TASK\n"); printf("9 - QUIT\n"); option_number = checkInput(); while(option_number == false){ checkInput(); } if (option_number == 1) { time_t start = time(NULL); analizeText(start, option); } else if (option_number == 2){ return false; } return false; } int checkInput() { int length,i; scanf ("%s", input); length =(int) strlen (input); for (i=0;i<length; i++){ if (!isdigit(input[i])){ printf("(Numbers 1,2 or 9 only.)\n"); return false; } else if(input[i] != '1' && input[i] != '2' && input[i] != '9') { printf("Please type 1,2 or 9.\n"); return false; } else if (input[i] == '9'){ printf("THANK YOU AND GOOD LUCK!!!\n"); exit(0); } else if (input[i] == '1') option_number = 1; else if (input[i] == '2') option_number = 2; } return option_number; }
C
//较第一版的优化 //1、界面优化 //2、通讯录存放的数据动态开辟,节省空间 //3、排序方式灵活 //4、做了各种异常处理,增加健壮性 #include <stdio.h> #include <string.h> #include <memory.h> #include <assert.h> #include <stdlib.h> #define NAME 8 #define SEX 5 #define PHONE 12 #define ADDR 20 #define DEFAULT 5 typedef struct people { char name[NAME]; char sex[SEX]; int age; char phone[PHONE]; char addr[ADDR]; }people; typedef struct contact { people* data; int num;//当前通讯录的有效人数(即目前实际放了多少人) int mem;//当前通讯录的有效内存容量(即可以放多少人) }contact; //通讯录初始化 void initContact(contact* c); //通讯录功能实现 void add(contact* c); void show(contact* c); void del(contact* c); void search(contact* c); void modify(contact* c); void clear(contact* c); void sort(contact* c); //通讯录销毁 void destoryContacy(contact* c);
C
/* Linker Errors If you receive a linker error, it means that your code compiles fine, but that some function or library that is needed cannot be found. This occurs in what we call the linking stage and will prevent an executable from being generated. Many compilers do both the compiling and this linking stage. Example 1: You misspell the name of a function (or method) when you declare, define or call it: void Foo(); int main() { Foo(); return 0; } void foo() { // do something } so that the linker complains: somefile.o(address): undefined reference to `Foo(void)' that it can't find it.} */ #include<stdio.h> int Add(int a,int b) { return a+b; } int main() { int a,b; a=8; b=9; printf("add = %d",add(a,b)); }
C
/** \file [board.h] \brief Contient la déclaration des fonctions, procédures, accesseurs et mutateurs, et la structure d'une board \author {Damotte Alan, Chaussende Adrien} \version 1.0 \date Avril 2013 */ #ifndef BOARD_H #define BOARD_H #include "piece.h" /* * FREE : indique que le point du tableau est vide * FILLED: indique que le point du tableau contient un bloc (1 ou 2) */ /** @enum Visited */ enum { FREE = 0, FILLED }; /** @struct Board @brief Structure d'une Board */ typedef struct { Piece * currentPiece; /* Pièce actuellement sur la grille*/ int gridge[20][10]; /* Grille de jeu*/ }Board; /* Mutateurs & Accesseurs */ /** @brief Mutateur de la piece @param pointeur sur une Board et pointeur sur une Piece */ void setCurrentPiece (Board * board, const Piece * piece); /** @brief Assesseur de la piece @param pointeur sur une Board @return pointeur sur une Piece */ Piece * getCurrentPiece (const Board * board); /* Autres méthodes */ /** @brief Initialise une Board @param pointeur sur une Board */ void initBoard (Board * board); /** @brief Free une Board @param pointeur sur une Board */ void freeBoard (Board * board); #endif
C
#include<stdio.h> main() { char s[20]; char c; int i = 0; while ((c = getchar()) != EOF && (c != ' ') && (c != '\n')) { s[i++] = c; } s[i] = ' '; printf("%d\n", htoi(s)); } int htoi(char s[]) { int d = 0, e = 0, f; if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) { d = 2; } int j = 0; while (s[j++] != ' ') { } f = j - 2; for (int i = 1; f >= d; i = i * 16) { if (s[f] >= '0' && s[f] <= '9') { e = e + (s[f] - '0') * i; } else if (s[f] >= 'a' && s[f] <= 'f') { e = e + (s[f] - 'a' + 10) * i; } else if (s[f] >= 'A' && s[f] <= 'F') { e = e + (s[f] - 'A' + 10) * i; } f--; } return e; }
C
/* date = November 29th 2020 4:14 pm */ #ifndef RAY_H #define RAY_H struct Ray{ Vec3 origin; Vec3 direction; }; Vec3 RayAt(Ray ray, f32 t){ Vec3 pos = ray.origin + (ray.direction*t); return pos; } Vec3 RayBackground(Ray ray){ Vec3 unit_direction = NormaliseVec3(ray.direction); f32 t = 0.5*(unit_direction.y + 1.0f); return Vec3(1.0f - t, 1.0f - t, 1.0f - t) + Vec3(127.0f / 255.0f, 178.0f / 255.0f, 1.0f) * t; } enum Materials{ DIFFUSE, METAL, GLASS }; enum Models{ SPHERE, PLANE }; struct HitInfo{ f32 root; Vec3 pos; Vec3 normal; b32 front_face; }; struct Model{ u32 type; Vec3 colour; u32 material; union{ /* Sphere */ struct{ Vec3 origin; f32 radius; }; /* Plane */ struct{ Vec3 point; Vec3 normal; f32 d; }; }; }; /* Need to specify a point on the plane and a normal */ Model CreatePlane(Vec3 point, Vec3 normal, Vec3 colour){ Model plane = {}; plane.type = PLANE; plane.point = point; plane.normal = normal; plane.colour = colour; plane.d = -Vec3Dot(point, normal); plane.material = DIFFUSE; return plane; } Model CreateSphere(Vec3 origin, f32 radius, Vec3 colour){ Model sphere = {}; sphere.type = SPHERE; sphere.origin = origin; sphere.radius = radius; sphere.colour = colour; //default type sphere.type = DIFFUSE; return sphere; } b32 SphereHit(Ray ray, Model sphere, HitInfo *hit_info){ //calculate sphere intersection f32 a = Vec3Dot(ray.direction, ray.direction); f32 b = 2.0f * Vec3Dot(ray.direction, ray.origin - sphere.origin); f32 c = Vec3Dot(ray.origin - sphere.origin, ray.origin - sphere.origin) - (sphere.radius * sphere.radius); f32 discriminant = b*b - 4*a*c; if(discriminant <= 0) return 0; else{ f32 root_1 = (-b - sqrt(discriminant)) / (2.0f * a); f32 root_2 = (-b + sqrt(discriminant)) / (2.0f * a); f32 tolerance = 0.001f; if(root_1 < tolerance && root_2 > tolerance){ hit_info->root = root_2; }else if(root_2 < tolerance && root_1 > tolerance){ hit_info->root = root_1; }else if((root_1 > tolerance) && (root_2 > tolerance)){ if(root_1 < root_2) hit_info->root = root_1; else hit_info->root = root_2; }else{ return 0; } hit_info->pos = RayAt(ray, hit_info->root); hit_info->normal = NormaliseVec3(RayAt(ray, hit_info->root) - sphere.origin); if(Vec3Dot(ray.direction, hit_info->normal) > 0.0f){ //ray is inside(back face) - reverse normal to point against ray hit_info->normal = Vec3(-hit_info->normal.x, -hit_info->normal.y, -hit_info->normal.z); hit_info->front_face = 0; }else{ //ray is outside - front face hit_info->front_face = 1; } return 1; } } b32 PlaneHit(Ray ray, Model plane, HitInfo *hit_info){ // plane equation: ax + by + cz + d = 0, where n = (a, b, c) plane.normal = NormaliseVec3(plane.normal); ray.direction = NormaliseVec3(ray.direction); f32 denom = Vec3Dot(plane.normal, ray.direction); if((denom < -0.0001f) > (denom > 0.0001f)){ hit_info->root = (-plane.d - Vec3Dot(plane.normal, ray.origin))/denom; if(hit_info->root > 0){ hit_info->pos = RayAt(ray, hit_info->root); hit_info->normal = plane.normal; return 1; }else{ return 0; } }else{ return 0; } } struct Camera{ Vec3 pos; f32 viewport_height; f32 viewport_width; f32 focal_length; Vec3 horizontal; Vec3 vertical; Vec3 lower_left_corner; }; Camera CreateCamera(Vec3 pos, Vec3 up, Vec3 look_at){ Camera camera = {}; camera.pos = pos; camera.viewport_height = 2.0; camera.viewport_width = (16.0f / 9.0f) * camera.viewport_height; camera.focal_length = 1.0f; Vec3 camera_z = NormaliseVec3(pos - look_at); Vec3 camera_x = NormaliseVec3(Vec3Cross(up, camera_z)); Vec3 camera_y = NormaliseVec3(Vec3Cross(camera_z, camera_x)); camera.horizontal = camera_x * camera.viewport_width; camera.vertical = camera_y * camera.viewport_height; camera.lower_left_corner = camera.pos - Vec3(camera.horizontal.x / 2.0f, camera.horizontal.y / 2.0f, camera.horizontal.z / 2.0f) - Vec3(camera.vertical.x / 2.0f, camera.vertical.y / 2.0f, camera.vertical.z / 2.0f) - camera_z; //camera.lower_left_corner = camera.lower_left_corner - w; return camera; } struct World{ Camera camera; u32 model_count; Model *models; }; Ray GetRay(Camera camera, f32 u, f32 v){ Ray ray = {}; ray.origin = camera.pos; ray.direction = camera.lower_left_corner + (camera.horizontal*u) + (camera.vertical*v) - camera.pos; return ray; } Vec3 GetRandomUnitSpherePoint(){ Vec3 sphere_point = {}; b32 found = 0; while(!found){ f32 x = (RandomFloat() * 2.0f) - 1; f32 y = (RandomFloat() * 2.0f) - 1; f32 z = (RandomFloat() * 2.0f) - 1; if((x*x+y*y+z*z) <= 1){ sphere_point.x = x; sphere_point.y = y; sphere_point.z = z; found = 1; } } return sphere_point; } Vec3 GetRandomUnitVector(){ return NormaliseVec3(GetRandomUnitSpherePoint()); } Vec3 GetRandomInHemisphere(Vec3 normal){ Vec3 unit_sphere_point = GetRandomUnitSpherePoint(); if(Vec3Dot(unit_sphere_point, normal) > 0.0){ return unit_sphere_point; }else{ return Vec3(-unit_sphere_point.x, -unit_sphere_point.y, -unit_sphere_point.z); } } b32 ModelHit(Ray ray, Model model, HitInfo *hit_info){ switch(model.type){ case(SPHERE):{ return SphereHit(ray, model, hit_info); } break; case(PLANE):{ return PlaneHit(ray, model, hit_info); } break; default:{ return 0; }; }; } void AddModel(World *world, Model model){ if(world->model_count >= MAX_MODELS){ printf("Model limit reached"); }else{ world->models[world->model_count++] = model; } } /* Thread work */ struct Job{ World *world; Image *image; int x_start; int y_start; int x_end; int y_end; }; struct JobQueue{ u32 job_count; Job *jobs; u32 chunks_per_row; volatile u64 current_job_index; volatile u64 jobs_finished; volatile u64 rows_finished; }; #endif //RAY_H
C
#include <stdio.h> void put(char *s, char *str, int ret) { printf("]\n"); printf("%s, %s\n", s, str); printf("ret=%d\n", ret); printf("--------\n"); } int main(void) { int ret; char *str = NULL; printf("-----------------s\n"); ret = printf("%s", "ryojiro"); put("%s", "ryojiro", ret); ret = printf("%.s", "ryojiro"); put("%.s", "ryojiro", ret); ret = printf("%10.s", "ryojiro"); put("%10.s", "ryojiro", ret); ret = printf("%.s", str); put("%.s", str, ret); ret = printf("%.0s", "ryojiro"); put("%.0s", "ryojiro", ret); ret = printf("%.3s", "ryojiro"); put("%.3s", "ryojiro", ret); ret = printf("%.10s", "ryojiro"); put("%.10s", "ryojiro", ret); ret = printf("%.10s", str); put("%.10s", str, ret); ret = printf("%1s", "ryojiro"); put("%1s", "ryojiro", ret); ret = printf("%10s", "ryojiro"); put("%10s", "ryojiro", ret); ret = printf("%10s", str); put("%10s", str, ret); ret = printf("%10.3s", "ryojiro"); put("%10.3s", "ryojiro", ret); ret = printf("%10.5s", "ryojiro"); put("%10.5s", "ryojiro", ret); ret = printf("%10.15s", "ryojiro"); put("%10.15s", "ryojiro", ret); ret = printf("%-10.5s", "ryojiro"); put("%-10.5s", "ryojiro", ret); ret = printf("%------------10.5s", "ryojiro"); put("%------------10.5s", "ryojiro", ret); ret = printf("%.*s", -1, str); put("%.*s , -1", str, ret); ret = printf("%.*s", -1, "ryojiro"); put("%.*s , -1", "ryojiro", ret); ret = printf("%.*s", 0, "ryojiro"); put("%.*s, 0", "ryojiro", ret); ret = printf("%3s", str); put("%3s", str, ret); ret = printf("%3.3s", str); put("%3.3s", str, ret); ret = printf("%*.*s", 10, -3, "ryojiro"); put("%*.*s , 10, -3", "ryojiro", ret); ret = printf("%*.*s", -10, 5, "ryojiro"); put("%*.*s , -10, 5", "ryojiro", ret); ret = printf("%-*.*s", -10, 5, "ryojiro"); put("%-*.*s ,-10, 5", "ryojiro", ret); ret = printf("%*s", 0, "ryojiro"); put("%*s , 0", "ryojiro", ret); ret = printf("abc%10.10sabc", "ryojiro"); put("abc%10.10sabc", "ryojiro", ret); ret = printf(""); put("\"\"", "", ret); ret = printf("%10%"); put("\"%10%\"", "%10%", ret); //recognized as flag 0 and flag 0 is undefined but molminette test this ret = printf("%0s", "ryojiro"); ret = printf("%010.5s", "ryojiro"); return (0); }
C
/Authored by Grant Slatton on 2013 September 13 //All code is released to the public domain under the terms of [http://unlicense.org] #include <string.h> #include <stdio.h> #include <stdlib.h> #include <vector> #include <utility> //returns a pair <direction, coordinate> where direction is North, Northeast, etc (clockwise) //and coordinate is in the form x*8 + y std::vector< std::pair<int, int> > get_directions(int board[][8], int x, int y, int color) { std::vector< std::pair<int, int> > directions; if(board[x][y]) { return directions; } //north if((y < 6) && (board[x][y+1] == -color)) { for(int i=y+2; i < 8; i++) { if(!board[x][i]) { break; } else if(board[x][i] == color) { directions.push_back(std::make_pair<int, int>(0, x*8+i)); break; } } } //northeast if((y < 6) && (x < 6) && (board[x+1][y+1] == -color)) { for(int i=0; (x+i+2 < 8) && (y+i+2 < 8); i++) { if(!board[x+i+2][y+i+2]) { break; } else if(board[x+i+2][y+i+2] == color) { directions.push_back(std::make_pair<int, int>(1, (x+i+2)*8+(y+i+2))); break; } } } //east if((x < 6) && (board[x+1][y] == -color)) { for(int i=x+2; i < 8; i++) { if(!board[i][y]) { break; } else if(board[i][y] == color) { directions.push_back(std::make_pair<int, int>(2, i*8+y)); break; } } } //southeast if((y > 1) && (x < 6) && (board[x+1][y-1] == -color)) { for(int i=0; (x+i+2 < 8) && (y-i-2 >= 0); i++) { if(!board[x+i+2][y-i-2]) { break; } else if(board[x+i+2][y-i-2] == color) { directions.push_back(std::make_pair<int, int>(3, (x+i+2)*8+(y-i-2))); break; } } } //south if((y > 1) && (board[x][y-1] == -color)) { for(int i=y-2; i >= 0; i--) { if(!board[x][i]) { break; } else if(board[x][i] == color) { directions.push_back(std::make_pair<int, int>(4, x*8+i)); break; } } } //southwest if((y > 1) && (x > 1) && (board[x-1][y-1] == -color)) { for(int i=0; (x-i-2 >= 0) && (y-i-2 >= 0); i++) { if(!board[x-i-2][y-i-2]) { break; } else if(board[x-i-2][y-i-2] == color) { directions.push_back(std::make_pair<int, int>(5, (x-i-2)*8+(y-i-2))); break; } } } //west if((x > 1) && (board[x-1][y] == -color)) { for(int i=x-2; i >= 0; i--) { if(!board[i][y]) { break; } else if(board[i][y] == color) { directions.push_back(std::make_pair<int, int>(6, i*8+y)); break; } } } //northwest if((y < 6) && (x > 1) && (board[x-1][y+1] == -color)) { for(int i=0; (x-i-2 >= 0) && (y+i+2 < 8); i++) { if(!board[x-i-2][y+i+2]) { break; } else if(board[x-i-2][y+i+2] == color) { directions.push_back(std::make_pair<int, int>(7, (x-i-2)*8+(y+i+2))); break; } } } return directions; } //returns all moves for a players on the current board. Each pair has a coordinate in the form //x*8+y, and a vector of pairs, each pair contains a direction and an endpoint in the form x*8+y std::vector< std::pair<int, std::vector< std::pair<int, int> > > > get_moves(int board[][8], int color) { std::vector< std::pair<int, std::vector< std::pair<int, int> > > > moves; for(int i=0; i < 8; i++) { for(int j=0; j < 8; j++) { moves.push_back(std::make_pair<int, std::vector< std::pair<int, int> > >(i*8+j, get_directions(board, i, j, color))); if(!moves.back().second.size()) { moves.pop_back(); } } } return moves; } //makes a move and flips the appropriate pieces void make_move(int board[][8], int x, int y, int color, std::vector< std::pair<int, int> > directions) { for(auto it=directions.begin(); it != directions.end(); it++) { int i = x; int j = y; while((i != ((*it).second/8)) || (j != ((*it).second&7))) { board[i][j] = color; if(i < ((*it).second/8)) { i++; } else if((i > (*it).second/8)) { i--; } if(j < ((*it).second&7)) { j++; } else if(j > ((*it).second&7)) { j--; } } } } //undoes a move (needs directions data so it can unflip stuff) void undo_move(int board[][8], int x, int y, int color, std::vector< std::pair<int, int> > directions) { for(auto it=directions.begin(); it != directions.end(); it++) { int i = x; int j = y; while((i != ((*it).second/8)) || (j != ((*it).second&7))) { board[i][j] = -color; if(i < ((*it).second/8)) { i++; } else if((i > (*it).second/8)) { i--; } if(j < ((*it).second&7)) { j++; } else if(j > ((*it).second&7)) { j--; } } board[i][j] = color; } board[x][y] = 0; } void print(int board[][8]) { for(int i=7; i >= 0; i--) { printf("%d ", i); for(int j=0; j < 8; j++) { if(!board[j][i]) { printf("-"); } else if(board[j][i] == 1) { printf("O"); } else { printf("X"); } } printf("\n"); } printf(" "); for(int i=0; i < 8; i++) { printf("%d", i); } printf("\n\n"); } int score(int board[][8], int color) { int sum = 0; for(int i=0; i < 8; i++) { for(int j=0; j < 8; j++) { sum += board[i][j]; } } return sum * color; } //Largely the same pseudocode from the negamax wikipedia article, but adapted for the rules of othello int negamax_aux(int board[][8], int color, int depth, int alpha, int beta) { if(depth == 0) { return score(board, color); } std::vector< std::pair<int, std::vector< std::pair<int, int> > > > moves = get_moves(board, color); if(moves.size() == 0) { if(get_moves(board, -color).size() == 0) { return score(board, color); } int val = -negamax_aux(board, -color, depth-1, -beta, -alpha); if(val >= beta) { return val; } if(val > alpha) { alpha = val; } } else { for(auto it=moves.begin(); it != moves.end(); it++) { make_move(board, (*it).first/8, (*it).first&7, color, (*it).second); int val = -negamax_aux(board, -color, depth-1, -beta, -alpha); undo_move(board, (*it).first/8, (*it).first&7, color, (*it).second); if(val >= beta) { return val; } if(val > alpha) { alpha = val; } } } return alpha; } //parent function to negamax_aux, this function actually maintains the current best move int negamax(int board[][8], int color, int depth) { int alpha = -65; int beta = 65; std::vector< std::pair<int, std::vector< std::pair<int, int> > > > moves = get_moves(board, color); int move = moves[0].first; for(auto it=moves.begin(); it != moves.end(); it++) { make_move(board, (*it).first/8, (*it).first&7, color, (*it).second); int val = -negamax_aux(board, -color, depth-1, -beta, -alpha); undo_move(board, (*it).first/8, (*it).first&7, color, (*it).second); if(val >= beta) { return (*it).first; } if(val > alpha) { alpha = val; move = (*it).first; } } return move; } //run with ./reversi [int] where int is the number of ply the AI searches deep. Default is 3 ply. int main(int argc, char **argv) { int depth = 3; if(argc > 1) { depth = atol(argv[1]); } depth *= 2; int board[8][8]; memset(board, 0, sizeof(board)); board[3][3] = board[4][4] = -1; board[3][4] = board[4][3] = 1; int turn = -1; while(true) { print(board); std::vector< std::pair<int, std::vector< std::pair<int, int> > > > moves= get_moves(board, turn); printf("available moves: "); for(auto it=moves.begin(); it != moves.end(); it++) { printf("(%d, %d) ", (*it).first/8, (*it).first%8); } printf("\n"); if(moves.size() == 0) { turn = -turn; moves = get_moves(board, turn); if(moves.size() == 0) { printf("final score: %d\n", score(board, -1)); return 0; } } else { int x, y; if(turn == -1) { scanf("%d %d", &x, &y); for(auto it=moves.begin(); it != moves.end(); it++) { if(x*8+y == ((*it).first)) { printf("chose: %d %d\n", x, y); make_move(board, x, y, turn, (*it).second); turn = -turn; break; } } } else { x = negamax(board, turn, depth); for(auto it=moves.begin(); it != moves.end(); it++) { if(x == ((*it).first)) { printf("chose: %d %d\n", x/8, x%8); make_move(board, x/8, x%8, turn, (*it).second); turn = -turn; break; } } } } } return 0; } //Music while coding: //Willow Beats - (All of their music) //https://soundcloud.com/willowbeats // //Peter Kusiv - Someone Told Me //https://soundcloud.com/peer-kusiv/peer-kusiv-someone-told-me
C
int mapmatching(int mapstate, int gameState, int mx, int my) // To Match The Place According To Value Of mapstate { if (mx >= 735 + 50 && mx <= 772 + 50 && my >= 278 && my <= 291 && gameState == 0) { mapstate = 0; } if (mx >= 778 && mx <= 806 && my >= 210 && my <= 233 && gameState == 0) { mapstate = 1; } if (mx >= 798 + 50 && mx <= 826 + 50 && my >= 227 && my <= 250 && gameState == 0) { mapstate = 2; } if (mx >= 855 + 50 && mx <= 888 + 50 && my >= 219 && my <= 244 && gameState == 0) { mapstate = 3; } if (mx >= 765 + 50 && mx <= 800 + 50 && my >= 175 && my <= 185 && gameState == 0) { mapstate = 4; } if (mx >= 641 + 50 && mx <= 695 + 50 && my >= 193 && my <= 254 && gameState == 0) { mapstate = 5; } if (mx >= 665 + 50 && mx <= 692 + 50 && my >= 266 && my <= 292 && gameState == 0) { mapstate = 6; } if (mx >= 588 + 50 && mx <= 610 + 50 && my >= 299 && my <= 319 && gameState == 0) { mapstate = 7; } if (mx >= 616 + 50 && mx <= 638 + 50 && my >= 301 && my <= 327 && gameState == 0) { mapstate = 8; } if (mx >= 647 + 50 && mx <= 663 + 50 && my >= 314 && my <= 333 && gameState == 0) { mapstate = 9; } if (mx >= 552 + 50 && mx <= 564 + 50 && my >= 598 + 150 - 309 && my <= 598 + 150 - 302 && gameState == 0) { mapstate = 10; } if (mx >= 557 + 50 && mx <= 573 + 50 && my >= 326 && my <= 340 && gameState == 0) { mapstate = 11; } if (mx >= 543 + 50 && mx <= 563 + 50 && my >= 598 + 150 - 451 && my <= 598 + 150 - 440 && gameState == 0) { mapstate = 12; } if (mx >= 574 + 50 && mx <= 605 + 50 && my >= 363 && my <= 410 && gameState == 0) { mapstate = 13; } if (mx >= 523 + 50 && mx <= 544 + 50 && my >= 434 && my <= 451 && gameState == 0) { mapstate = 14; } if (mx >= 465 + 50 && mx <= 492 + 50 && my >= 598 + 150 - 443 && my <= 598 + 150 - 428 && gameState == 0) { mapstate = 15; } if (mx >= 311 + 50 && mx <= 363 + 50 && my >= 598 + 150 - 411 && my <= 598 + 150 - 360 && gameState == 0) { mapstate = 16; } if (mx >= 230 + 50 && mx <= 283 + 50 && my >= 598 + 150 - 321 && my <= 598 + 150 - 301 && gameState == 0) { mapstate = 17; } if (mx >= 446 + 50 && mx <= 462 + 50 && my >= 598 + 150 - 201 && my <= 598 + 150 - 191 && gameState == 0) { mapstate = 18; } if (mx >= 391 + 50 && mx <= 436 + 50 && my >= 544 && my <= 569 && gameState == 0) { mapstate = 19; } if (mx >= 379 + 50 && mx <= 452 + 50 && my >= 573 && my <= 607 && gameState == 0) { mapstate = 20; } if (mx >= 457 + 50 && mx <= 475 + 50 && my >= 560 && my <= 573 && gameState == 0) { mapstate = 21; } if (mx >= 372 + 50 && mx <= 419 + 50 && my >= 623 && my <= 643 && gameState == 0) { mapstate = 22; } if (mx >= 253 + 50 && mx <= 290 + 50 && my >= 559 && my <= 598 && gameState == 0) { mapstate = 23; } if (mx >= 307 + 50 && mx <= 352 + 50 && my >= 619 && my <= 646 && gameState == 0) { mapstate = 24; } if (mx >= 320 + 50 && mx <= 355 + 50 && my >= 657 && my <= 679 && gameState == 0) { mapstate = 25; } if (mx >= 486 + 50 && mx <= 508 + 50 && my >= 610 && my <= 622 && gameState == 0) { mapstate = 26; } return mapstate; } void mapDes(int mapstate, char place[][100], char placePic[][100]) { FILE *fp; iShowBMP(0, 0, "bgmap.bmp"); iShowBMP(500, 550, placePic[mapstate]); iSetColor(0, 0, 0); iShowBMP(50, 700, "backs button.bmp"); fp = fopen(place[mapstate], "r"); char str[300]; int i = 0; int j = 500; fgets(str, 300, fp); while (!feof(fp)) { iText(20, j, str, GLUT_BITMAP_HELVETICA_18); fgets(str, 300, fp); j = j - 20; } fclose(fp); } void map(int mapstate, char place[][100], char placePic[][100]) // To Show The Place Details { if (mapstate == 0) { mapDes(mapstate, place, placePic); } if (mapstate == 1) { mapDes(mapstate, place, placePic); } if (mapstate == 2) { mapDes(mapstate, place, placePic); } if (mapstate == 3) { mapDes(mapstate, place, placePic); } if (mapstate == 4) { mapDes(mapstate, place, placePic); } if (mapstate == 5) { mapDes(mapstate, place, placePic); } if (mapstate == 6) { mapDes(mapstate, place, placePic); } if (mapstate == 7) { mapDes(mapstate, place, placePic); } if (mapstate == 8) { mapDes(mapstate, place, placePic); } if (mapstate == 9) { mapDes(mapstate, place, placePic); } if (mapstate == 10) { mapDes(mapstate, place, placePic); } if (mapstate == 11) { mapDes(mapstate, place, placePic); } if (mapstate == 12) { mapDes(mapstate, place, placePic); } if (mapstate == 13) { mapDes(mapstate, place, placePic); } if (mapstate == 14) { mapDes(mapstate, place, placePic); } if (mapstate == 15) { mapDes(mapstate, place, placePic); } if (mapstate == 16) { mapDes(mapstate, place, placePic); } if (mapstate == 17) { mapDes(mapstate, place, placePic); } if (mapstate == 18) { mapDes(mapstate, place, placePic); } if (mapstate == 19) { mapDes(mapstate, place, placePic); } if (mapstate == 20) { mapDes(mapstate, place, placePic); } if (mapstate == 21) { mapDes(mapstate, place, placePic); } if (mapstate == 22) { mapDes(mapstate, place, placePic); } if (mapstate == 23) { mapDes(mapstate, place, placePic); } if (mapstate == 24) { mapDes(mapstate, place, placePic); } if (mapstate == 25) { mapDes(mapstate, place, placePic); } if (mapstate == 26) { mapDes(mapstate, place, placePic); } }
C
#include <string.h> #include <stdio.h> #include <stdlib.h> #include <bt-memory.h> #include <bt-util.h> #ifndef SYSCONFDIR #define SYSCONFDIR "/etc" #endif #define MAP_FILES_DIRECTORY SYSCONFDIR "/bt/players.data/" typedef struct bt_oc_map_item_ru { char *name; int id; } bt_oc_map_item_ru; typedef struct bt_oc_map_ru { bt_oc_map_item_ru *items; size_t count; } bt_oc_map_ru; void bt_oc_map_ru_free(bt_oc_map_ru *map) { if (map == NULL) return; for (size_t idx = 0; idx < map->count; ++idx) { bt_oc_map_item_ru *item; item = &map->items[idx]; bt_free(item->name); } bt_free(map->items); bt_free(map); } static bt_oc_map_ru * bt_oc_map_ru_new(size_t count) { bt_oc_map_ru *map; map = bt_malloc(sizeof(*map)); if (map == NULL) return NULL; map->items = bt_malloc(count * sizeof(*map->items)); if (map->items == NULL) map->items = NULL; map->count = count; return map; } static int bt_oc_map_ru_compare(const void *const lhs, const void *const rhs) { return strcmp(((bt_oc_map_item_ru *) lhs)->name, ((bt_oc_map_item_ru *) rhs)->name); } static void bt_oc_map_ru_sort(bt_oc_map_ru *map) { if (map->items == NULL) return; qsort(map->items, map->count, sizeof(*map->items), bt_oc_map_ru_compare); } bt_oc_map_item_ru * bt_oc_map_ru_find(bt_oc_map_ru *map, const char *const name) { bt_oc_map_item_ru item; if (map == NULL) return NULL; item.name = (char *) name; return bsearch(&item, map->items, map->count, sizeof(*map->items), bt_oc_map_ru_compare); } static bt_oc_map_ru * bt_oncourt_map_load(const char *const filepath) { size_t count; char name[100]; bt_oc_map_ru *atp; int id; FILE *file; file = fopen(filepath, "r"); if (file == NULL) return NULL; count = 0; while (fscanf(file, "%99[^|]|%d", name, &id) == 2) { if (*name == '#') continue; count += 1; } atp = bt_oc_map_ru_new(count); if (atp == NULL) goto error; rewind(file); count = 0; while (fscanf(file, "%99[^|]|%d", name, &id) == 2) { bt_oc_map_item_ru *item; size_t length; if (*name == '#') continue; item = &atp->items[count]; length = strlen(name); item->name = bt_stripdup(name, &length); item->id = id; count += 1; } bt_oc_map_ru_sort(atp); error: fclose(file); return atp; } bt_oc_map_ru * bt_oc_map_load_atp(void) { return bt_oncourt_map_load(MAP_FILES_DIRECTORY "atp.txt"); } bt_oc_map_ru * bt_oc_map_load_wta(void) { return bt_oncourt_map_load(MAP_FILES_DIRECTORY "wta.txt"); } int bt_oc_map_item_ru_get_id(bt_oc_map_item_ru *item) { return item->id; }
C
/* Assume you have a method isSubstring which checks if one word is a substring of another. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring. e.g. "waterbottle" is a rotation of "erbottlewat". */ # include <stdlib.h> # include <string.h> int areRotations (char str1[], char str2[]) { int len = strlen(str1); char *doubleStr2; int yup; if (len != strlen(str2)) return 0; doubleStr2 = malloc(2*len + 1); memcpy(doubleStr2, str2, len); memcpy(doubleStr2 + len, str2, len); doubleStr2[2*len] = '\0'; yup = (strstr(doubleStr2, str1) != NULL); free(doubleStr2); return yup; }
C
/* * $Id: pmemcpy.c,v 1.1 2005-09-18 22:05:43 dhmunro Exp $ * memcpy that p_mallocs its destination */ /* Copyright (c) 2005, The Regents of the University of California. * All rights reserved. * This file is part of yorick (http://yorick.sourceforge.net). * Read the accompanying LICENSE file for details. */ #include "config.h" #include "pstdlib.h" #include <string.h> void * p_memcpy(const void *s, size_t n) { if (s) { void *d = p_malloc(n); if ( ! (((char *)s-(char *)0) & (sizeof(size_t)-1)) ) { /* some versions of memcpy miss this obvious optimization */ const size_t *sl=s; size_t *dl=d; while (n>=sizeof(size_t)) { *(dl++)= *(sl++); n -= sizeof(size_t); } } if (n) memcpy(d, s, n); return d; } else { return 0; } }
C
/* Módulo de definición de 'TLista'. Se definen las listas de elementos de tipo 'info_t'. Laboratorio de Programación 2. InCo-FIng-UDELAR */ #ifndef _LISTA_H #define _LISTA_H #include "utils.h" // Representación de 'TLista'. // Se debe definir en listaInfo.cpp. // struct repLista; // Declaración del tipo 'TLista'. typedef struct repLista *TLista; /* Operaciones de TLista */ /* Devuelve un elemento de tipo 'TLista' vacío (sin elementos). */ TLista crearLista(); /* Devuelve la cantidad de elementos de 'lista'. */ nat longitud(TLista lista); /* Si longitud(lista) < MAX (definido en utils.h) y 1 <= pos <= longitud(lista) + 1 inserta 'info' en la posiicón 'pos' de 'lista'. Devuelve 'lista'. */ TLista insertar(nat pos, info_t info, TLista lista); /* Si 1 <= pos <= longitud(lista) remueve de 'lista' el elemento que está en la posición 'pos'. Devuelve 'lista'. */ TLista remover(nat pos, TLista lista); /* Devuelve la posición del primer elemento de 'lista' cuyo componente natural es igual a 'elem', o 0 si 'elem' no está en 'lista'. */ nat posNat(nat elem, TLista lista); /* Devuelve el elemenos que está en la posición 'pos' de 'lista'. Precondición 1 <= pos <= longitud(lista). */ info_t infoLista(nat pos, TLista lista); #endif
C
#include <stdio.h> #include <stdlib.h> /* * 1: candidato 1 * 2: candidato 2 * 3: candidato 3 * 4: candidato 4 * 5: candidato 5 * * 0: voto en blanco */ int main(int argc, char const *argv[]) { unsigned int votos[6] = {0, 0, 0, 0, 0, 0}; int candidato = 0; while (candidato >= 0) { printf("Ingrese el numero de su candidato favorito: "); scanf("%d", &candidato); switch (candidato) { case -1: printf("Iniciando conteo...\n"); break; case 0: votos[0]++; break; case 1: votos[1]++; break; case 2: votos[2]++; break; case 3: votos[3]++; break; case 4: votos[4]++; break; case 5: votos[5]++; break; default: printf("El candidato %d no esta registrado\n", candidato); break; } } unsigned int total = 0; for (uint i = 0; i < 6; i++) { total += votos[i]; } float porcentajes[6] = { ((float) votos[0] / total) * 100, ((float) votos[1] / total) * 100, ((float) votos[2] / total) * 100, ((float) votos[3] / total) * 100, ((float) votos[4] / total) * 100, ((float) votos[5] / total) * 100 }; printf("Total de votantes: %d\n", total); printf("\n\nCandidato 1: %d votos -- Porcentaje: %.2f", votos[1], porcentajes[1]); printf("\nCandidato 2: %d votos -- Porcentaje: %.2f", votos[2], porcentajes[2]); printf("\nCandidato 3: %d votos -- Porcentaje: %.2f", votos[3], porcentajes[3]); printf("\nCandidato 4: %d votos -- Porcentaje: %.2f", votos[4], porcentajes[4]); printf("\nCandidato 5: %d votos -- Porcentaje: %.2f", votos[5], porcentajes[5]); printf("\nNulos: %d votos -- Porcentaje: %.2f", votos[0], porcentajes[0]); printf("\n\nGracias.\n"); return EXIT_SUCCESS; }
C
/* Partner(s) Name & E-mail: Andres Sanchez * Lab Section: B21 * Assignment: Lab # 2 Exercise # 2-3 * Exercise Description: [optional - include for your own benefit] * * I acknowledge all content contained herein, excluding template or example * code, is my own original work. */ #include <avr/io.h> //on register x set bit k to bit b unsigned char SetBit(unsigned char x, unsigned char k, unsigned char b) { return (b ? x | (0x01 << k) : x & ~(0x01 << k)); } //GetBit returns the value of bit k in register x unsigned char GetBit(unsigned char x, unsigned char k) { return ((x & (0x01 << k)) != 0); } int main(void) { DDRA = 0x00; PORTA = 0xFF; // Configure port A's 8 pins as inputs DDRC = 0xFF; PORTC = 0x00; // Configure port B's 8 pins as outputs, // initialize to 0s unsigned char tmpC = 0x00; // intermediate variable used for port updates unsigned char tmpA = 0x00; /* Replace with your application code */ while (1) { tmpA = PINA & 0x0F; if (tmpA == 0x00){ tmpC = 0x00; } else if (tmpA < 0x03){ tmpC = 0x20; } else if (tmpA < 0x05){ tmpC = 0x30; } else if (tmpA < 0x07){ tmpC = 0x38; } else if (tmpA < 0x0A){ tmpC = 0x3C; } else if (tmpA < 0x0D){ tmpC = 0x3E; } else { tmpC = 0x3F; } //for the low light button if (tmpA < 0x04){ tmpC = (tmpC & 0x3F) | 0x40; } //on register x set bit k to bit b //unsigned char SetBit(unsigned char x, unsigned char k, unsigned char b) { //if (GetBit(tmpA,4) == 1 && GetBit(tmpA,5) == 1 && GetBit(tmpA,6) == 0){ //SetBit(tmpC,7,1); //} tmpA = PINA & 0x70; if (tmpA == 0x30){ tmpC = (tmpC & 0x7F) | 0x80; } PORTC = tmpC; } }
C
#include "../../include/my.h" #include "polyList.h" int main() { STATUS status; DOUBLE_LIST *pResultList, *pMulList; LP_DOUBLE_LIST pInsertNode; int n; int k; printf("Input a data which you want to calculate factorial\n"); n = 10;//scanf("%d", &n); if (n <= 0) { Print(("Input data is less than 1\n")); exit(-1); } initList(&pResultList); pInsertNode = (LP_DOUBLE_LIST)malloc(sizeof(DOUBLE_LIST)); if (NULL == pInsertNode) { Print(("OutOfMemory when copyList\n")); return -2; } pInsertNode->factor = 1; pInsertNode->nIndex = 0; pResultList->pNextNode = pInsertNode; pInsertNode->pNextNode = pResultList; k = 2; initList(&pMulList); while(k <= n) { if (setMulList(pMulList, k) != 0) { Print(("OutOfMemory when set mulList ,here k is %d\n", k)); exit(-1); } mulSelfList(pResultList, pMulList); cleanList(pMulList); k++; } printf("\n %d! = ", n); printPolyList(pResultList); putchar('\n'); destoryList(pResultList); destoryList(pMulList); return 0; } STATUS initList(LP_DOUBLE_LIST *ppListHead) { *ppListHead = (LP_DOUBLE_LIST)malloc(sizeof(DOUBLE_LIST)); if (NULL == *ppListHead) { Print(("Out Of Memory when allocate list head\n")) ; return ERROR; } (*ppListHead)->nIndex = -1; (*ppListHead)->pNextNode = *ppListHead; (*ppListHead)->pPrevNode = *ppListHead; return OK; } void printPolyList(const LP_DOUBLE_LIST pListHead) { LP_DOUBLE_LIST pIterNode = pListHead->pPrevNode; int curIndex = -1; while(pIterNode != pListHead) { if (curIndex > 0 && curIndex - 1 > pIterNode->nIndex) { while (--curIndex > pIterNode->nIndex) putchar('0'); } curIndex = pIterNode->nIndex; putchar(('0'+pIterNode->factor)); pIterNode = pIterNode->pPrevNode; } while(curIndex > 0 && curIndex--) { putchar('0'); } } void cleanList(LP_DOUBLE_LIST pListHead) { LP_DOUBLE_LIST pNextNode, pIterNode = pListHead->pNextNode; while (pIterNode != pListHead) { pNextNode = pIterNode->pNextNode; free(pIterNode); pIterNode = pNextNode; } pListHead->pNextNode = pListHead; } void destoryList(LP_DOUBLE_LIST pListHead) { LP_DOUBLE_LIST pNextNode, pIterNode = pListHead->pNextNode; while (pIterNode != pListHead) { pNextNode = pIterNode->pNextNode; free(pIterNode); pIterNode = pNextNode; } free(pListHead); } void insertNodeAfter(LP_DOUBLE_LIST pInsertPos, LP_DOUBLE_LIST pInsertNode) { pInsertNode->pNextNode = pInsertPos->pNextNode; pInsertNode->pPrevNode = pInsertPos; pInsertNode->pNextNode->pPrevNode = pInsertNode; pInsertPos->pNextNode = pInsertNode; } void deleteNode(LP_DOUBLE_LIST pDeleteNode) { LP_DOUBLE_LIST pPrevNode, pNextNode; if (pDeleteNode->pNextNode == pDeleteNode) { Print(("Error when delete a node\n")); exit(-1); } pPrevNode = pDeleteNode->pPrevNode; pNextNode = pDeleteNode->pNextNode; free(pDeleteNode); pPrevNode->pNextNode = pNextNode; pNextNode->pPrevNode = pPrevNode; } STATUS setMulList(LP_DOUBLE_LIST pListHead, unsigned int k) { unsigned int temp, index = 0; char c; LP_DOUBLE_LIST pInsertNode = NULL; LP_DOUBLE_LIST pInsertPos = pListHead; while(k) { temp = k%10; pInsertNode = (LP_DOUBLE_LIST)malloc(sizeof(DOUBLE_LIST)); if (NULL == pInsertNode) { Print(("OutOfMemory when add node in mul list\n")); return -2; } pInsertNode->factor = temp; pInsertNode->nIndex = index; pInsertNode->pPrevNode = pInsertPos; pInsertPos->pNextNode = pInsertNode; pInsertPos = pInsertNode; index++; k = k/10; } pInsertNode->pNextNode = pListHead; pListHead->pPrevNode = pInsertNode; return OK; } STATUS copyList(LP_DOUBLE_LIST pDst, LP_DOUBLE_LIST pSrc) { LP_DOUBLE_LIST pIterNode = pSrc->pNextNode; LP_DOUBLE_LIST pInsertNodePrev = pDst; LP_DOUBLE_LIST pInsertNode; while(pIterNode != pSrc) { pInsertNode = (LP_DOUBLE_LIST)malloc(sizeof(DOUBLE_LIST)); if (NULL == pInsertNode) { Print(("OutOfMemory when copyList\n")); return -2; } pInsertNode->factor = pIterNode->factor; pInsertNode->nIndex = pIterNode->nIndex; pInsertNode->pPrevNode = pInsertNodePrev; pInsertNodePrev->pNextNode = pInsertNode; pInsertNodePrev = pInsertNode; pIterNode = pIterNode->pNextNode; } pInsertNodePrev->pNextNode = pDst; pDst->pPrevNode = pInsertNodePrev; return OK; } STATUS mulOneNode(LP_DOUBLE_LIST pDst, LP_DOUBLE_LIST pSrc, LP_DOUBLE_LIST pNode) { LP_DOUBLE_LIST pIterNode, pInsertNode, pInsertPos; BOOL bHaveAcc = FALSE; int accIndex = 0, accFactor = 0; pInsertPos = pDst; if (pNode->factor) { pIterNode = pSrc->pNextNode; while (pIterNode != pSrc) { pInsertNode = (LP_DOUBLE_LIST)malloc(sizeof(DOUBLE_LIST)); if (NULL == pInsertNode) { Print(("OutOfMemory when mulOneNode\n")); return -2; } pInsertNode->factor = pIterNode->factor*pNode->factor; pInsertNode->nIndex = pIterNode->nIndex+pNode->nIndex; if (bHaveAcc) { LP_DOUBLE_LIST pInsertAccNode; bHaveAcc = FALSE; if (accIndex == pInsertNode->nIndex) { pInsertNode->factor += accFactor; } else { pInsertAccNode = (LP_DOUBLE_LIST)malloc(sizeof(DOUBLE_LIST)); if (NULL == pInsertAccNode) { Print(("OutOfMemory when mulOneNode\n")); return -2; } pInsertAccNode->factor = accFactor; pInsertAccNode->nIndex = accIndex; insertNodeAfter(pInsertPos, pInsertAccNode); pInsertPos = pInsertAccNode; } } if (pInsertNode->factor >= 10) { bHaveAcc = TRUE; accIndex = pInsertNode->nIndex + 1; accFactor = pInsertNode->factor/10; pInsertNode->factor %= 10; } if (pInsertNode->factor == 0) { free(pInsertNode); } else { insertNodeAfter(pInsertPos, pInsertNode); pInsertPos = pInsertNode; } pIterNode = pIterNode->pNextNode; } if (bHaveAcc) { LP_DOUBLE_LIST pInsertAccNode; bHaveAcc = FALSE; pInsertAccNode = (LP_DOUBLE_LIST)malloc(sizeof(DOUBLE_LIST)); if (NULL == pInsertAccNode) { Print(("OutOfMemory when mulOneNode\n")); return -2; } pInsertAccNode->factor = accFactor; pInsertAccNode->nIndex = accIndex; insertNodeAfter(pInsertPos, pInsertAccNode); pInsertPos = pInsertAccNode; } } return OK; } STATUS addToList(LP_DOUBLE_LIST pResultList, LP_DOUBLE_LIST pAddSrcList) { LP_DOUBLE_LIST pIterNode = pAddSrcList->pNextNode; LP_DOUBLE_LIST pInsertPos = pResultList, pInsertNode; while (pIterNode != pAddSrcList) { while (pInsertPos->pNextNode != pResultList && pInsertPos->pNextNode->nIndex < pIterNode->nIndex) { pInsertPos = pInsertPos->pNextNode; } if (pInsertPos->pNextNode != pResultList && pInsertPos->pNextNode->nIndex == pIterNode->nIndex) { pInsertPos->pNextNode->factor += pIterNode->factor; if (pInsertPos->pNextNode->factor >= 10) { if (pInsertPos->pNextNode->pNextNode != pResultList && pInsertPos->pNextNode->pNextNode->nIndex == pIterNode->nIndex + 1) { pInsertPos->pNextNode->pNextNode->factor += 1; } else { LP_DOUBLE_LIST pInsertAccNode = (LP_DOUBLE_LIST)malloc(sizeof(DOUBLE_LIST)); if (NULL == pInsertAccNode) { Print(("OutOfMemory in addToList\n")); return -2; } pInsertAccNode->factor = 1; pInsertAccNode->nIndex = pIterNode->nIndex+1; insertNodeAfter(pInsertPos->pNextNode, pInsertAccNode); } pInsertPos->pNextNode->factor %= 10; if (pInsertPos->pNextNode->factor == 0) { deleteNode(pInsertPos->pNextNode); } } pInsertPos = pInsertPos->pNextNode; } else { pInsertNode = (LP_DOUBLE_LIST)malloc(sizeof(DOUBLE_LIST)); if (NULL == pInsertNode) { Print(("OutOfMemory in add List\n")); return -2; } pInsertNode->factor = pIterNode->factor; pInsertNode->nIndex = pIterNode->nIndex; insertNodeAfter(pInsertPos, pInsertNode); pInsertPos = pInsertNode; pInsertPos = pInsertNode; } pIterNode = pIterNode->pNextNode; } return OK; } STATUS mulSelfList(LP_DOUBLE_LIST pResultList,LP_DOUBLE_LIST pMulSrcList) { LP_DOUBLE_LIST pOriList, pIterNode; LP_DOUBLE_LIST pTempResultList; initList(&pOriList); initList(&pTempResultList); copyList(pOriList, pResultList); cleanList(pResultList); pIterNode = pMulSrcList->pNextNode; while (pIterNode != pMulSrcList) { mulOneNode(pTempResultList, pOriList, pIterNode); addToList(pResultList, pTempResultList); cleanList(pTempResultList); pIterNode = pIterNode->pNextNode; } destoryList(pOriList); destoryList(pTempResultList); return OK; }
C
/** * @fle Standard IO * @author treelite(c.xinle@gmail.com) */ #include <stdio.h> #include <string.h> static const int VGA_ADDRESS = 0xB8000; void print(char *str) { int len = strlen(str); char *p; p = (char *)VGA_ADDRESS; for (int i = 0; i < len; i++) { *p = str[i]; p++; *p = 7; p++; } }
C
#include <string.h> #include "kernel.h" static int devfs_mount(struct fs *this, struct dev *dev, uint32_t addr); static int devfs_unmount(struct fs *this); static int devfs_open(struct fs *this, char *name, int mode, struct file **_fpp); static int devfs_close (struct file *_fp); static int devfs_read (struct file *_fp, uint8_t *buf, size_t size); static int devfs_write (struct file *_fp, uint8_t *buf, size_t size); static int devfs_seek (struct file *_fp, off_t offset, int whence); static int devfs_ioctl (struct file *_fp, uint32_t cmd, void *arg); struct dev_file { struct file file; struct dev *dev; int mode; uint32_t pointer; }; struct dev_fs { struct fs fs; } dev_fs = { { .mount = devfs_mount, .unmount = devfs_unmount, .open = devfs_open, .close = devfs_close, .read = devfs_read, .write = devfs_write, .seek = devfs_seek, .ioctl = devfs_ioctl } }; static int devfs_mount(struct fs *this, struct dev *dev, uint32_t addr) { return 0; } static int devfs_unmount(struct fs *this) { return 0; } static int devfs_open(struct fs *this, char *name, int mode, struct file **_fpp) { int i; char fullname[16]; if(mode & O_APPEND) return -1; for(i = 0; i < NR_DEVICE; i++) { if(g_dev_vector[i] == NULL) continue; snprintf(fullname, sizeof(fullname), "%s%d", g_dev_vector[i]->drv->major, g_dev_vector[i]->minor); if(strncmp(fullname, name, strlen(fullname)) == 0) break; } if(i == NR_DEVICE) return -1; if(g_dev_vector[i]->drv->attach(g_dev_vector[i]) != 0) return -1; struct dev_file *fp = (struct dev_file *) kmalloc(sizeof(struct dev_file)); fp->file.fs = this; fp->dev = g_dev_vector[i]; fp->pointer = 0; fp->mode = mode; *_fpp = (struct file *)fp; return 0; } static int devfs_close (struct file *_fp) { struct dev_file *fp = (struct dev_file *)_fp; kfree(fp); return 0; } static int devfs_read(struct file *_fp, uint8_t *buf, size_t size) { struct dev_file *fp = (struct dev_file *)_fp; if((fp->mode & 1) != O_RDONLY) return -1; int retval = fp->dev->drv->read(fp->dev, fp->pointer, buf, size); if(retval >= 0) { fp->pointer += retval; return retval; } return retval; } static int devfs_write (struct file *_fp, uint8_t *buf, size_t size) { struct dev_file *fp = (struct dev_file *)_fp; if(((fp->mode & 1) != O_WRONLY) && ((fp->mode & 2) != O_RDWR)) return -1; int retval = fp->dev->drv->write(fp->dev, fp->pointer, buf, size); if(retval >= 0) { fp->pointer += retval; return retval; } return retval; } static int devfs_seek (struct file *_fp, off_t offset, int whence) { struct dev_file *fp = (struct dev_file *)_fp; switch(whence) { case SEEK_SET: fp->pointer = offset; break; case SEEK_CUR: fp->pointer += offset; break; default: return -1; } return fp->pointer; } static int devfs_ioctl (struct file *_fp, uint32_t cmd, void *arg) { struct dev_file *fp = (struct dev_file *)_fp; return fp->dev->drv->ioctl(fp->dev, cmd, arg); }
C
#include "systick_lib.h" #include "gp_drive.h" #include "stm32f10x.h" #include "uart_drive.h" #include "str_lib.h" /* UART manager: 0-count incrementing each itme we receive msg 1-signal variable to detreermine wheather msg is ready 2-bridge vairable to confirm bridge condition or not 3-Terminator should 1:Termianator /0:Interrupt flag to decide wheather to choose terminaton character or interrupt timer termination for msg 4-terminator char specified char vales as terminator charactewr 5-time const value time to wait after interr 6-time counter this value will be decremeted this should really be done using the structure but he wants to keep it simple C so no structs here, only arays so this mgr arrays should beported in the future to using struct variables or bitfields even in struct */ /* static char USART_1_msg[250]; static unsigned short USART_1_cnt=0; static unsigned short USART_1_sig=0; static unsigned short USART_1_bdg=0; */ unsigned short uart_1_mgr[7]={0,0,0,0,0,0,0}; static char USART_2_msg[250]; //static unsigned short USART_2_cnt=0; //static unsigned short USART_2_sig=0; //static unsigned short USART_2_bdg=0; unsigned short uart_2_mgr[7]={0,0,0,1,'\n',0,0}; static char USART_3_msg[250]; //static unsigned short USART_3_cnt=0; //static unsigned short USART_3_sig=0; //static unsigned short USART_3_bdg=0; unsigned short uart_3_mgr[7]={0,0,0,1,'\n',0,0}; //static static char chat; //static static char msg[30]="welcome to the weew!\n"; //static static char msg1[30]="welcome to the noob!\n"; static volatile int sgnl=0; static volatile _Bool val1=0; static volatile _Bool tst1val=0; static volatile int val3=0; char str1_tst[12]; int main(void) { systick_init(); UART_init(2,9600); UART_init(3,9600); delay_MS(100); //time delay in order to seet the registers UART_send(2,"this is uart 2");//nucle com6 UART_send(3,"this is uart 3");//adapter com10 int2str(2597,str1_tst); val3=char2int("2597"); while(1) { //receive char: //chat=UART_rx(3); //transmiit: //UART_tx(3,chat); // delay_MS(100); if(uart_2_mgr[1]==1) { // UART_send(3,USART_2_msg); tst1val=str_findL("Weew","Weewk"); sgnl=str_len(USART_2_msg); val1=str_find("hehe",USART_2_msg); uart_2_mgr[1]=0; str_empty(USART_2_msg); //CLEAR_ the string for sending no errors when shorter msg than previous } if(uart_3_mgr[1]==1) { // UART_send(2,USART_3_msg); uart_3_mgr[1]=0; str_empty(USART_3_msg); //CLEAR_BIT the string for sending } } } void USART2_IRQHandler() { UART_isr(2,uart_2_mgr,USART_2_msg); } void USART3_IRQHandler() { UART_isr(3,uart_3_mgr,USART_3_msg); } void SysTick_Handler(void) { //to nie jest najlepsze rozwiazanie bo trzeba tracic miejsce na strukture do usarta1 mimo ze go sie nie uzywa i on sprawdza potem i probuje go odczytywac? //odczytu nie ma chyba bo flaga [0] zawsze na 0 systick_inter(uart_1_mgr,uart_2_mgr,uart_3_mgr); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_dictresize.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: thplessi <thplessi@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/02/14 02:06:20 by thplessi #+# #+# */ /* Updated: 2017/02/14 14:56:37 by thplessi ### ########.fr */ /* */ /* ************************************************************************** */ #include <ft_dict.h> /* ** This function resize the given dictionary to the given size. ** Return: NULL if there is an error. ** The resized dictionary if not. */ t_dict ft_dictresize(t_dict dict, size_t size) { t_dict tmp; tmp = ft_dictsnew(size); if (!tmp) return (NULL); ft_dictrehash(tmp, dict); free(dict->table); dict->size = tmp->size; dict->table = tmp->table; free(tmp); return (dict); }
C
#include "sort.h" /** * partition - the partition that will be done by our quicksort * @array: the array given * @low: the lowest number. * @highest: the highest number * @size: Size of the array * Return: the integer used for the partition */ int partition(int *array, int low, int highest, size_t size) { int pivoter = array[highest], i = low, j, tmp; for (j = low; j < highest; j++) { if (array[j] < pivoter) { if (i != j) { tmp = array[i]; array[i] = array[j]; array[j] = tmp; print_array(array, size); } i++; } } if (array[highest] < array[i]) { tmp = array[i]; array[i] = array[highest]; array[highest] = tmp; print_array(array, size); } return (i); } /** * quicksort - implements the quicksort functions * @array: the array that will be sorted * @low: the lowest point in the array * @highest: the highest point of the array * @size: The size of the array */ void quicksort(int *array, int low, int highest, size_t size) { int pivot; if (low < highest) { pivot = partition(array, low, highest, size); quicksort(array, low, pivot - 1, size); quicksort(array, pivot + 1, highest, size); } } /** * quick_sort - the base function in which we will call our * quicksort * @array: the array given * @size: the size of the array */ void quick_sort(int *array, size_t size) { if (array != NULL || size > 1) quicksort(array, 0, size - 1, size); }
C
// // Created by Fabian, Moritz on 17.04.18. // #include "OSMP.h" #include <sys/mman.h> #include <fcntl.h> #include <sys/stat.h> #include <semaphore.h> #ifdef __APPLE__ #include <zconf.h> #endif #ifdef __linux__ #include <unistd.h> #endif #include <string.h> #include <errno.h> #include <math.h> #include "int_to_string.h" static sem_t* read_semaphore = NULL, * write_semaphore = NULL, * messages_semaphore = NULL; struct stat shared_memory_file_stat; static SHARED_MEMORY* shared_memory = NULL; static unsigned int current_rank; static sem_t** messages_semaphores = NULL; static char** messages_name_semaphores = NULL; static sem_t** messages_limit_semaphores = NULL; static char** messages_name_limit_semaphores = NULL; /** * Adds the message index to the given index storage * @param first_last the index storage * @param index the index of the message to add */ void add_message(FIRST_LAST* first_last, int index) { if (first_last->first == -1) { // First message first_last->first = index; // On first message, last and first is identically first_last->last = index; } else { // There's already an first message shared_memory->messages[first_last->last].next = index; // Add the next message as an next of the last message first_last->last = index; // Message is now the last message } } /** * Removes the message index from the given index storage * @param first_last the index storage * @param index the index of the message to remove */ void remove_message(FIRST_LAST* first_last, int index) { // Declare next free index from message previous next free message first_last->first = shared_memory->messages[index].next; if (first_last->first == -1) { // When there is not first message, there is no last message first_last->last = -1; } } /** * Resets an message to bring it back to it's initial state * @param message the message to reset */ void reset_message(MESSAGE* message) { message->next = -1; } /** * Fill the given message with the data, size, source and destination * @param message the message to send * @param buffer the data of the message * @param size the size of the data * @param source the source process index of the message * @param destination the destination of the message */ void fill_message(MESSAGE* message, const void* buffer, size_t size, unsigned int source, unsigned int destination) { memcpy(message->data, buffer, size); message->length = size; message->source = source; message->destination = destination; reset_message(message); } /** * Reads the given message and pass back the data, size, source and length * @param message message to read * @param buffer the buffer of the message * @param size the size of the message * @param source the source process index of the message * @param len the length of the message */ void read_message(MESSAGE* message, void* buffer, size_t size, unsigned int* source, size_t* len) { memcpy(buffer, message->data, size); *source = message->source; *len = message->length; reset_message(message); } /** * Checks if the OSMP library got initialized * ``` * int main(int argc, char* argv[]) { * if (OSMP_Init(&argc, &argv) == OSMP_ERROR) return EXIT_FAILURE; * ... * } * ``` * @return {@link OSMP_SUCCESS} when initialized else {@link OSMP_ERROR} */ int check_init() { if (shared_memory == NULL || read_semaphore == NULL || write_semaphore == NULL) { printf("OSMP_Init() needs to be called first"); return OSMP_ERROR; } return OSMP_SUCCESS; } int OSMP_Init(int* argc, char*** argv) { printf("%s", "OSMP_Init()\n"); int fd = shm_open(SHARED_MEMORY_NAME, O_RDWR, 0); if (fd < 1) { printf("shm_open(): %s\n", strerror(errno)); return OSMP_ERROR; } if (fstat(fd, &shared_memory_file_stat) < 0) { printf("fstat(): %s\n", strerror(errno)); return OSMP_ERROR; } shared_memory = (SHARED_MEMORY*) mmap(NULL, (size_t) shared_memory_file_stat.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (shared_memory == MAP_FAILED) { printf("mmap(): %s\n", strerror(errno)); return OSMP_ERROR; } read_semaphore = sem_open(MEMORY_READ_SEMAPHORE_NAME, O_CREAT, 0644, 1); write_semaphore = sem_open(MEMORY_WRITE_SEMAPHORE_NAME, O_CREAT, 0644, 1); messages_semaphore = sem_open(MESSAGES_SEMAPHORE_NAME, O_CREAT, 0644, OSMP_MAX_SLOTS); pid_t pid = getpid(); unsigned int length = shared_memory->header.size; messages_semaphores = malloc(sizeof(sem_t*) * length); messages_name_semaphores = malloc(sizeof(char*) * length); messages_limit_semaphores = malloc(sizeof(sem_t*) * length); messages_name_limit_semaphores = malloc(sizeof(char*) * length); for (unsigned int i = 0; i < length; i++) { if (shared_memory->header.processes[i].process_id == pid) { current_rank = i; } char* ptr; char* sem_rank = intToString(i, &ptr); char* sem_name = malloc(sizeof(char) * (strlen(MESSAGES_SEMAPHORE_NAME_PREFIX) + strlen(sem_rank)) + 1); strcpy(sem_name, MESSAGES_SEMAPHORE_NAME_PREFIX); strcat(sem_name, sem_rank); messages_semaphores[i] = sem_open(sem_name, O_CREAT, 0644, 0); messages_name_semaphores[i] = sem_name; sem_name = malloc(sizeof(char) * (strlen(MESSAGES_SEMAPHORE_LIMIT_NAME_PREFIX) + strlen(sem_rank)) + 1); strcpy(sem_name, MESSAGES_SEMAPHORE_LIMIT_NAME_PREFIX); strcat(sem_name, sem_rank); messages_limit_semaphores[i] = sem_open(sem_name, O_CREAT, 0644, OSMP_MAX_MESSAGES_PROC); messages_name_limit_semaphores[i] = sem_name; free(ptr); } return OSMP_SUCCESS; } int OSMP_Finalize(void) { if (check_init() == OSMP_ERROR) return OSMP_ERROR; sem_close(read_semaphore); //sem_unlink(MEMORY_READ_SEMAPHORE_NAME); sem_close(write_semaphore); //sem_unlink(MEMORY_WRITE_SEMAPHORE_NAME); for (unsigned int i = 0, length = shared_memory->header.size; i < length; i++) { sem_close(messages_semaphores[i]); sem_close(messages_limit_semaphores[i]); //sem_unlink(messages_name_semaphores[i]); free(messages_name_semaphores[i]); free(messages_name_limit_semaphores[i]); } free(messages_semaphores); free(messages_limit_semaphores); free(messages_name_semaphores); free(messages_name_limit_semaphores); munmap(shared_memory, (size_t) shared_memory_file_stat.st_size); shared_memory = NULL; read_semaphore = NULL; write_semaphore = NULL; messages_semaphores = NULL; messages_limit_semaphores = NULL; messages_name_semaphores = NULL; messages_name_limit_semaphores = NULL; return OSMP_SUCCESS; } int OSMP_Size(unsigned int* size) { if (check_init() == OSMP_ERROR) return OSMP_ERROR; *size = shared_memory->header.size; return OSMP_SUCCESS; } int OSMP_Rank(unsigned int* rank) { if (check_init() == OSMP_ERROR) return OSMP_ERROR; *rank = current_rank; return OSMP_SUCCESS; } int OSMP_Send(const void* buffer, size_t size, unsigned int dest) { if (size > OSMP_MAX_PAYLOAD_LENGTH) { printf("size > OSMP_MAX_PAYLOAD_LENGTH(%d)\n", OSMP_MAX_PAYLOAD_LENGTH); return OSMP_ERROR; } if (check_init() == OSMP_ERROR) return OSMP_ERROR; sem_wait(messages_limit_semaphores[dest]); sem_wait(messages_semaphore); //printf("Send() Start\n"); sem_wait(write_semaphore); // wait until there's no writers sem_wait(read_semaphore); // wait until there's no readers // Write message int first_free_index = shared_memory->header.first_last_free.first; if (first_free_index == -1) { printf("No message slot available\n"); return OSMP_ERROR; } remove_message(&shared_memory->header.first_last_free, first_free_index); fill_message(&shared_memory->messages[first_free_index], buffer, size, current_rank, dest); add_message(&shared_memory->header.processes[dest].first_last_msg, first_free_index); sem_post(read_semaphore); // signal other readers can run sem_post(write_semaphore); // signal other writers can run sem_post(messages_semaphores[dest]); return OSMP_SUCCESS; } int OSMP_Recv(void* buffer, size_t size, unsigned int* source, size_t* len) { //printf("Recv() Start\n"); if (check_init() == OSMP_ERROR) return OSMP_ERROR; sem_wait(messages_semaphores[current_rank]); sem_wait(write_semaphore); // wait until there's no writers sem_post(read_semaphore); // there's one more reader active //printf("Recv_sem_wait() Start\n"); //printf("Recv_sem_wait() End\n"); // Read message int first_msg_index = shared_memory->header.processes[current_rank].first_last_msg.first; if (first_msg_index == -1) { printf("No message received\n"); return OSMP_ERROR; } remove_message(&shared_memory->header.processes[current_rank].first_last_msg, first_msg_index); read_message(&shared_memory->messages[first_msg_index], buffer, size, source, len); add_message(&shared_memory->header.first_last_free, first_msg_index); sem_wait(read_semaphore); // this reader is completed sem_post(write_semaphore); // signal other writers can run sem_post(messages_semaphore); sem_post(messages_limit_semaphores[current_rank]); //printf("Recv() End\n"); return OSMP_SUCCESS; } SHARED_MEMORY* OSMP_Get_Shared_Memory() { if (check_init() == OSMP_ERROR) return NULL; return shared_memory; }
C
/* ************************************************************************** */ /* */ /* :::::::: */ /* ft_sort_small.c :+: :+: */ /* +:+ */ /* By: dsaripap <marvin@codam.nl> +#+ */ /* +#+ */ /* Created: 2020/03/12 13:46:56 by dsaripap #+# #+# */ /* Updated: 2020/06/07 10:24:55 by dsaripap ######## odam.nl */ /* */ /* ************************************************************************** */ #include "../includes/push_swap.h" /* ** Sorting function that is called when Stack_A ** has only 3 numbers so then there are only ** 6 possible permutations */ void ft_sort_three(t_prgm *prgm) { t_stack_list *a; t_stack_list *b; t_stack_list *c; a = prgm->stacks->stacka_lst; b = prgm->stacks->stacka_lst->next; c = prgm->stacks->stacka_lst->next->next; if ((a->num > b->num) && (b->num > c->num)) { ft_rotate_a(prgm); ft_swap_a(prgm); } else if ((a->num < b->num) && (b->num > c->num) && (c->num < a->num)) ft_reverserotate_a(prgm); else if ((a->num < b->num) && (b->num > c->num) && (c->num > a->num)) { ft_swap_a(prgm); ft_rotate_a(prgm); } else if ((a->num > b->num) && (b->num < c->num) && (c->num > a->num)) ft_swap_a(prgm); else if ((a->num > b->num) && (b->num < c->num) && (c->num < a->num)) ft_rotate_a(prgm); } /* ** Sorting function that is called when the amount of numbers ** that we want to sort is less than 10 */ static int ft_sort_lt_ten(t_prgm *prgm) { int counter; counter = 0; while (prgm->stacka_len > 3) { ft_move_num_to_top_of_stack(prgm, 0); if (ft_check_ifsorted(prgm) == SUCCESS) return (SUCCESS); ft_push_b(prgm); counter++; } ft_sort_three(prgm); while (counter > 0) { ft_push_a(prgm); counter--; } return (CONTINUE); } int ft_sort_small(t_prgm *prgm) { t_stack_list *temp; temp = prgm->stacks->stacka_lst; if (prgm->stacka_len == 1) { return (0); } else if (prgm->stacka_len == 2) { if (temp->num > temp->next->num) ft_swap_a(prgm); return (0); } else if (prgm->stacka_len == 3) ft_sort_three(prgm); else if ((prgm->stacka_len > 3) && (prgm->stacka_len <= 10)) ft_sort_lt_ten(prgm); return (SUCCESS); }
C
/* ** EPITECH PROJECT, 2020 ** B-PSU-101-BAR-1-1-minishell1-leon.ducasse ** File description: ** cd.c */ #include "mysh.h" control_t *my_cd(control_t *control, char **arg) { char *old = get_pwd(control); if (size_array(arg) > 2) { put_error(CD_MANY_ARG); return (control); } if (!arg[1] || my_strcmp(arg[1], "") == 0 || my_strcmp(arg[1], "--") == 0) { if (chdir(get_home(control)) == -1) return (control); control = my_set_env(control, get_arr_arg("HOME", get_home(control))); } else if (my_strcmp(arg[1], "-") == 0) { if (chdir(get_oldpwd(control)) == -1) return (control); control = my_set_env(control, get_arr_arg("PWD", get_pwd(control))); } else { if (chdir(my_strcat(put_slash(get_pwd(control)), arg[1])) == -1) { put_error(my_strcat(arg[1], ERR_CD)); return (control); } } return (my_set_env(control, get_arr_arg("OLDPWD", old))); }
C
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> void transverter(); int main(){ transverter(); system("pause"); return 0; } void transverter(){ char input = ' '; printf("תĸ\n"); while (1){ scanf("%c", &input); if ((input > 64 && input<91)){ printf("%cСдĸ%c\n", input, (input + 32)); continue; } else if (input>96 && input < 123){ printf("%cĴдĸ%c\n", input, (input - 32)); continue; } else if (input>47&&input<58) { continue; } else { continue; } } return 0; } //void menu(){ // printf("****************************\n"); // printf("**********1.start***********\n"); // printf("**********2.exit************\n"); // printf("****************************\n"); //} // //void guss_num(){ // int num; // int key = rand() % 100 + 1; // while (1){ // printf("\n"); // scanf("%d", &num); // if (num > key){ // printf("´\n"); // } // else if (num < key){ // // printf("С\n"); // // } // else{ // printf("¶~~\n"); // break; // } // } //} // //int main(){ // int choose; // do{ // menu(); // scanf("%d", &choose); // // switch (choose) // { // case 1: // guss_num(); // break; // case 2: // exit(0); // break; // default: // printf("\n"); // menu(); // break; // } // } while (choose); // // srand((unsigned)time(null)); // // system("pause"); // return 0; //}
C
#include<stdio.h> #include <stdlib.h> #include "my_set.h" void print_set(NumbersSet *set) { int i; printf("The set is :"); for (i = 0; i < set->size; i++) { printf("%d ", set->array[i]); } } void insert_to_set(NumbersSet *set, int num) { if (!is_in_set(set, num)) { set->array[set->size] = num; set->size++; } } int is_in_set(NumbersSet *set, int num) { int i; for (i = 0; i < set->size; i++) { if (set->array[i] == num) { return 1; } } return 0; } NumbersSet *init_set() { NumbersSet *set = (NumbersSet *) malloc(sizeof(NumbersSet)); set->size = 0; return set; } void get_set(NumbersSet *set) { int num; while (scanf("%d", &num) == 1) { printf("Number was scanned:%d\n", num); insert_to_set(set, num); } } int main() { NumbersSet *set = init_set(); get_set(set); print_set(set); free(set); return 0; }
C
#include<stdio.h> #include<string.h> int main() { char s1[11], s2[11]; scanf("%s", s1); strcpy(s2, s1); printf("%s\n", s1); printf("%s\n", s2); printf("%d\n", strlen(s1)); strcat(s1, s2); printf("%s\n", s1); return 0; }
C
/* Compile: make scanf Run: ./scanf make scanf && ./scanf */ #include <stdio.h> // declaration scanf function header int main(void) { int day = 0; int month = 0; int year = 0; int matches = scanf("%d.%d.%d", &day, &month, &year); printf("%d: %d %d %d\n", matches, day, month, year); return 0; }
C
//Prabhat kumar mahato //reg no: 11718252 //roll no:59 #include<pthread.h> #include<stdio.h> #include<semaphore.h> void *fun1(); void *fun2(); void *fa() { printf("Fa is completed\n"); } void *fb() { printf("Fb is completed\n"); } void *fc() { printf("Fc is completed\n"); } sem_t m; sem_t n; int main() { sem_init(&m,0,1); sem_init(&n,0,1); pthread_t thread1; pthread_create(&thread1, NULL, fun1, NULL); pthread_join(thread1, NULL); } void *fun1() { pthread_t thread2; pthread_create(&thread2, NULL, fun2, NULL); pthread_join(thread2, NULL); sem_wait(&m); //fb(); fc(); sem_post(&n); //P(m); //fb(); //V(n); } void *fun2() { fa(); sem_post(&m); sem_wait(&n); //fc(); fb(); //V(m); //P(n); //fc(); }
C
#include<stdio.h> #include <stdlib.h> #include <sys/time.h> #define MAX 1000000 double wtime() { struct timeval t; gettimeofday(&t, NULL); return (double)t.tv_sec + (double)t.tv_usec * 1E-6; } int getrand(int min, int max) { return (double)rand() / (RAND_MAX + 1.0) * (max - min) + min; } void max_heapify(int a[], int i, int heapsize) { int tmp, largest; int l = (2 * i) + 1; int r = (2 * i) + 2; if ((l <= heapsize) && (a[l] > a[i])) largest = l; else largest = i; if ((r <= heapsize) && (a[r] > a[largest])) largest = r ; if (largest != i) { tmp = a[i]; a[i] = a[largest]; a[largest] = tmp; max_heapify(a, largest, heapsize); } } void build_max_heap(int a[], int heapsize) { int i; for (i = heapsize/2; i >= 0; i--) { max_heapify(a, i, heapsize); } } void heap_sort(int a[], int heapsize) { double t; int g; int log=50000; t = wtime(); int i, tmp,l=950000; build_max_heap(a, heapsize); FILE *file; file=fopen("file1.dat","w"); for (i = heapsize; i > 0; i--) { if (i==l){ log=log+50000; g=t; t = wtime() - t; fprintf(file,"%d %.6f\n",log,t); printf("%.6f\n",t); t=g; l=l-50000; } tmp = a[i]; a[i] = a[0]; a[0] = tmp; heapsize--; max_heapify(a, 0, heapsize); } fclose(file); } int main() { int i, r, heapsize; int *a=(int*)malloc(MAX*sizeof(int)); double t; for (i=0;i<MAX;i++){ a[i]=getrand(1,1001); } heapsize = MAX - 1; heap_sort(a, heapsize); return 0; }
C
/* STDLIB2.C -- for BDS C v1.41 -- 10/14/80 This file contains the source for the following library functions: printf fprintf sprintf _spr scanf fscanf sscanf _scn fgets puts fputs swapin Note that all the upper-level formatted I/O functions ("printf", "fprintf", "scanf", and "fscanf") now use "_spr" and "_scn" for doing conversions. While this leads to very modularized source code, it also means that calls to "scanf" and "fscanf" must process ALL the information on a line of text; if the format string runs out and there is still text left in the line being processed, the text will be lost (i.e., the NEXT scanf or fscanf call will NOT find it.) An alternate version of "_spr" is given in the file FLOAT.C for use with floating point numbers; see FLOAT.C for details. Since "_spr" is used by "printf", this really amounts to an alternate version of "printf." Also note that temporary work space is declared within each of the high-level functions as a one-dimensional character array. The length limit on this array is presently set to 132 by the #define MAXLINE statement; if you intend to create longer lines through printf, fprintf, scanf, or fscanf calls, be SURE to raise this limit by changing the #define statement. Some misc. comments on hacking text files with CP/M: The conventional CP/M text format calls for each line to be terminated by a CR-LF combination. In the world of C programming, though, we like to just use a single LF (also called a newline) to terminate lines. AND SO, the functions which deal with reading and writing text lines from disk files to memory and vice-versa ("fgets", "fputs") take special pains to convert CR-LF combinations into single '\n' characters when reading from disk ("fgets"), and convert '\n' characters to CR-LF combinations when writing TO disk ("fputs"). This allows the C programmer to do things in style, dealing only with a single line terminator while the text is in memory, while maintaining compat- ibility with the CP/M text format for disk files (so that, for example, a text file can be "type"d under the CCP.) To confuse matters further, the "gets" function (which simply buffers up a line of console input) terminates a line with '\0' (a zero byte) instead of CR or LF. Thus, if you want to read in lines of input from the console and write them to a file, you'll have to manually put out the CR and LF at the end of every line ("gets" was designed this was to be compatible with the UNIX version). Remember to put out a 0x1a (control-Z, CPMEOF) at the end of text files being written out to disk. Also, watch out when reading in text files using "getc". While a text file is USUALLY terminated with a control-Z, it MAY NOT BE if the file ends on an even sector boundary (although respectable editors will now usually make sure the control-Z is always there.) This means that there are two possible return values from "getc" which can signal an End-of file: CPMEOF ( 0x1a, or control-Z), ERROR (-1, or 255 if you assign it to a char variable) should the CPMEOF (0x1a) be missing. */ #include "bdscio.h" char toupper(), isdigit(); /* printf usage: printf(format, arg1, arg2, ...); Note that since the "_spr" function is used to form the output string, and then "puts" is used to actually print it out, care must be taken to avoid generating null (zero) bytes in the output, since such a byte will terminate printing of the string by puts. Thus, a statment such as: printf("%c foo",'\0'); would print nothing at all. This is my latest version of the "printf" standard library routine. This time, folks, it REALLY IS standard. I've tried to make it EXACTLY the same as the version presented in Kernighan & Ritchie: right-justification of fields is now the default instead of left-justification (you can have left-justification by using a dash in the conversion, as specified in the book); the "%s" conversion can take a precision now as well as a field width; the "e" and "f" conversions, for floating point numbers, are supported in a special version of "_spr" given in source form in the FLOAT.C file. If you do a lot of number crunching and wish to have that version be the default (it eats up a K or two more than this version), just replace the version of "_spr" in DEFF.CRL with the one in FLOAT.C, using the CLIB program, or else be stuck with always typing in "float" on the clink command line... */ printf(format) char *format; { char line[MAXLINE]; _spr(line,&format); /* use "_spr" to form the output */ puts(line); /* and print out the line */ } /* scanf: This one accepts a line of input text from the console, and converts the text to the required binary or alphanumeric form (see Kernighan & Ritchie for a more thorough description): Usage: scanf(format, ptr1, ptr2, ...); Returns number of items matched. Since a new line of text must be entered from the console each time scanf is called, any unprocessed text left over from the last call is lost forever. This is a difference between BDS scanf and UNIX scanf. Another is that the field width specification is not supported here. */ int scanf(format) char *format; { char line[MAXLINE]; gets(line); /* get a line of input from user */ return _scn(line,&format); /* and scan it with "_scn" */ } /* fprintf: Like printf, except that the first argument is a pointer to a buffered I/O buffer, and the text is written to the file described by the buffer: ERROR (-1) returned on error. usage: fprintf(iobuf, format, arg1, arg2, ...); */ int fprintf(iobuf,format) char *format; struct _buf *iobuf; { char text[MAXLINE]; _spr(text,&format); return fputs(text,iobuf); } /* fscanf: Like scanf, except that the first argument is a pointer to a buffered input file buffer, and the text is taken from the file instead of from the console. Usage: fscanf(iobuf, format, ptr1, ptr2, ...); Returns number of items matched (zero on EOF.) Note that any unprocessed text is lost forever. Each time scanf is called, a new line of input is gotten from the file, and any information left over from the last call is wiped out. Thus, the text in the file must be arranged such that a single call to fscanf will always get all the required data on a line. This is not compatible with the way UNIX does things, but it eliminates the need for separate scanning functions for files, strings, and console input; it is more economical to let both "fscanf" and "scanf" use "sscanf". If you want to be able to scan a partial line with fscanf and have the rest still be there on the next fscanf call, you'll have to rewrite fscanf to be self contained (not use sscanf) and use "ungetc" to push back characters. Returns number of items succesfully matched. */ int fscanf(iobuf,format) char *format; struct _buf *iobuf; { char text[MAXLINE]; if (!fgets(text,iobuf)) return 0; return _scn(text,&format); } /* sprintf: Like fprintf, except a string pointer is specified instead of a buffer pointer. The text is written directly into memory where the string pointer points. Usage: sprintf(string,format,arg1, arg2, ...); */ sprintf(buffer,format) char *buffer, *format; { _spr(buffer,&format); /* call _spr to do all the work */ } /* sscanf: Reads a line of text in from the console and scans it for variable values specified in the format string. Uses "_scn" for actual conversions; see the comments below in the _scn function for more details. Usage: scanf(format,&arg1,&arg2,...); */ int sscanf(line,format) char *line, *format; { return _scn(line,&format); /* let _scn do all the work */ } /* General formatted output conversion routine, used by fprintf and sprintf..."line" is where the output is written, and "fmt" is a pointer to an argument list which must consist of a format string pointer and subsequent list of (optional) values. Having arguments passed on the stack works out a heck of a lot neater than it did before when the args were passed via an absolute vector in low memory! */ _spr(line,fmt) char *line, **fmt; { char _uspr(), c, base, *sptr, *format; char wbuf[MAXLINE], *wptr, pf, ljflag; int width, precision, *args; format = *fmt++; /* fmt first points to the format string */ args = fmt; /* now fmt points to the first arg value */ while (c = *format++) if (c == '%') { wptr = wbuf; precision = 6; ljflag = pf = 0; if (*format == '-') { format++; ljflag++; } width = (isdigit(*format)) ? _gv2(&format) : 1; if ((c = *format++) == '.') { precision = _gv2(&format); pf++; c = *format++; } switch(toupper(c)) { case 'D': if (*args < 0) { *wptr++ = '-'; *args = -*args; width--; } case 'U': base = 10; goto val; case 'X': base = 16; goto val; case 'O': base = 8; /* note that arbitrary bases can be added easily before this line */ val: width -= _uspr(&wptr,*args++,base); goto pad; case 'C': *wptr++ = *args++; width--; goto pad; case 'S': if (!pf) precision = 200; sptr = *args++; while (*sptr && precision) { *wptr++ = *sptr++; precision--; width--; } pad: *wptr = '\0'; pad2: wptr = wbuf; if (!ljflag) while (width-- > 0) *line++ = ' '; while (*line = *wptr++) line++; if (ljflag) while (width-- > 0) *line++ = ' '; break; default: *line++ = c; } } else *line++ = c; *line = '\0'; } /* Internal routine used by "_spr" to perform ascii- to-decimal conversion and update an associated pointer: */ int _gv2(sptr) char **sptr; { int n; n = 0; while (isdigit(**sptr)) n = 10 * n + *(*sptr)++ - '0'; return n; } /* Internal function which converts n into an ASCII base `base' representation and places the text at the location pointed to by the pointer pointed to by `string'. Yes, you read that correctly. */ char _uspr(string, n, base) char **string; unsigned n; { char length; if (n<base) { *(*string)++ = (n < 10) ? n + '0' : n + 55; return 1; } length = _uspr(string, n/base, base); _uspr(string, n%base, base); return length + 1; } /* General formatted input conversion routine. "line" points to a string containing ascii text to be converted, and "fmt" points to an argument list consisting of first a format string and then a list of pointers to the destination objects. Appropriate data is picked up from the text string and stored where the pointer arguments point according to the format string. See K&R for more info. The field width specification is not supported by this version. NOTE: the "%s" termination character has been changed from "any white space" to the character following the "%s" specification in the format string. That is, the call sscanf(string, "%s:", &str); would ignore leading white space (as is the case with all format conversions), and then read in ALL subsequent text (including newlines) into the buffer "str" until a COLON or null byte is encountered. */ int _scn(line,fmt) char *line, **fmt; { char sf, c, base, n, *sptr, *format; int sign, val, **args; format = *fmt++; /* fmt first points to the format string */ args = fmt; /* now it points to the arg list */ n = 0; while (c = *format++) { if (!*line) return n; /* if end of input string, return */ if (isspace(c)) continue; /* skip white space in format string */ if (c != '%') { /* if not %, must match text */ if (c != _igs(&line)) return n; else line++; } else { /* process conversion */ sign = 1; base = 10; sf = 0; if ((c = *format++) == '*') { sf++; /* if "*" given, supress assignment */ c = *format++; } switch (toupper(c)) { case 'X': base = 16; goto doval; case 'O': base = 8; goto doval; case 'D': if (_igs(&line) == '-') { sign = -1; line++; } doval: case 'U': val = 0; if (_bc(_igs(&line),base) == ERROR) return n; while ((c = _bc(*line++,base)) != 255) val = val * base + c; line--; break; case 'S': _igs(&line); sptr = *args; while (c = *line++) { if (c == *format) { format++; break; } if (!sf) *sptr++ = c; } if (!sf) { n++; *sptr = '\0'; args++; } continue; case 'C': if (!sf) { poke(*args++, *line); n++; } line++; continue; default: return n; } if (!sf) { **args++ = val * sign; n++; } }} return n; } /* Internal function to position the character pointer argument to the next non white-space character in the string: */ char _igs(sptr) char **sptr; { char c; while (isspace(c = **sptr)) ++*sptr; return (c); } /* Internal function to convert character c to value in base b , or return ERROR if illegal character for that base: */ int _bc(c,b) char c,b; { if (isalpha(c = toupper(c))) c -= 55; else if (isdigit(c)) c -= 0x30; else return ERROR; if (c > b-1) return ERROR; else return c; } /* puts: Write out the given string to the console. A newline is NOT automatically appended: */ puts(s) char *s; { while (*s) putchar(*s++); } /* fgets: This next function is like "gets", except that a) the line is taken from a buffered input file instead of from the console, and b) the newline is INCLUDED in the string and followed by a null byte. This one is a little tricky due to the CP/M convention of having a carriage-return AND a linefeed character at the end of every text line. In order to make text easier to deal with from C programs, this function (fgets) automatically strips off the CR from any CR-LF combinations that come in from the file. Any CR characters not im- mediately followed by LF are left intact. The LF is included as part of the string, and is followed by a null byte. (Note that LF equals "newline".) There is no limit to how long a line can be here; care should be taken to make sure the string pointer passed to fgets points to an area large enough to accept any possible line length (a line must be terminated by a newline (LF, or '\n') character before it is considered complete.) The value NULL (defined to be 0 here) is returned on EOF, whether it be a physical EOF (attempting to read past last sector of the file) OR a logical EOF (encountered a control-Z.) The 1.3 version didn't recognize logical EOFs, because I did't realize how SIMPLE it was to implement a buffered I/O "ungetc" function. */ char *fgets(s,iobuf) char *s; struct _buf *iobuf; { int count, c; char *cptr; count = MAXLINE; cptr = s; if ( (c = getc(iobuf)) == CPMEOF || c == EOF) return NULL; do { if ((*cptr++ = c) == '\n') { if (cptr>s+1 && *(cptr-2) == '\r') *(--cptr - 1) = '\n'; break; } } while (count-- && (c=getc(iobuf)) != EOF && c != CPMEOF); if (c == CPMEOF) ungetc(c,iobuf); /* push back control-Z */ *cptr = '\0'; return s; } /* fputs: This function writes a string out to a buffered output file. The '\n' character is expanded into a CR-LF combination, in keeping with the CP/M convention. If a null ('\0') byte is encountered before a newline is encountered, then there will be NO automatic termination character appended to the line. ERROR (-1) returned on error. */ fputs(s,iobuf) char *s; struct _buf *iobuf; { char c; while (c = *s++) { if (c == '\n') putc('\r',iobuf); if (putc(c,iobuf) == ERROR) return ERROR; } return OK; } /* swapin: This is the swapping routine, to be used by the root segment to swap in a code segment in the area of memory between the end of the root segment and the start of the external data area. See the document "SWAPPING.DOC" for detailed info on the swapping scheme. Returns ERROR (-1) on error, OK (0) if segment loaded in OK. This version does not check to make sure that the code yanked in doesn't overlap into the extenal data area (in the interests of keeping the function short.) But, if you'd like swapin to check for such problems, note that memory locations ram+115h and ram+116h contain the 16-bit address of the base of the external data area (low order byte first, as usual.) By rewriting swapin to read in one sector at a time and check the addresses, accidental overlap into the data area can be avoided. */ swapin(name,addr) char *name; /* the file to swap in */ { int fd; if (( fd = open(name,0)) == ERROR) { printf("Swapin: cannot open %s\n",name); return ERROR; } if ((read(fd,addr,9999)) < 0) { printf("Swapin: read error on %s\n",name); close(fd); return ERROR; } close(fd); return OK; } 
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include "pbPlots.h" #include "supportLib.h" /* This program does statistical analysis on data you input, either manually, through .txt file or through .bin file It can do Single variable statistics, multiple results statistics and linear regression. The program is highly optimized for both speed and memory, especially when reading .bin files. */ //datastructure for results statistics and linear regression typedef struct datastructure{ double data1; double data2; }dataset; //functions for finding mimimum and maximum of an array double min(double a[], unsigned long int length){ double minimum = a[0]; unsigned long int i=0; for(i=0; i<length; i++){ if(a[i]<minimum){ minimum = a[i]; } } return minimum; } double max(double a[], unsigned long int length){ double maximum = a[0]; unsigned long int i=0; for(i=0; i<length; i++){ if(a[i]>maximum){ maximum = a[i]; } } return maximum; } unsigned char num = 1; unsigned char num2 = 0; unsigned char main(){ //Initial user input, defines what the user wants the program to do START: printf("What do you need?\n1-Single variable stat.\n2-Results stat.\n3-Linear regression\n0-exit\n"); scanf("%hhu", &num); fflush(stdin); switch(num){ //exit case 0:{ return 0; } //Single variable statistics case 1:{ //initial definitions of important values unsigned long int i=0, k=0; double x_avg=0, m=0, M=0, R=0, x_med=0, del_x=0; double sum = 0; double* data = (double*)malloc(0); //sorting algorithm for quicksort signed char sortiranje(double* a, double* b) { if(*a<*b) return -1; else if(*a>*b) return 1; else return 0; } //Data reading definition printf("Do you want to read data from a file?\n1-Yes .txt file\n2-Yes .bin file\n0-No\n"); scanf("%hhu", &num); fflush(stdin); switch(num){ //Manual input case 0:{ i==1; printf("Insert sample vector: (you end by inserting non-number)\n"); data = (double*)realloc(data, sizeof(double)); printf("x[%lu]=", k+1); while(scanf(" %lf", &data[k])==1) { fflush(stdin); k++; i=0; data = (double*)realloc(data, sizeof(double)*(k+1)); printf("x[%lu]=", k+1); } fflush(stdin); data = (double*)realloc(data, sizeof(double)*k); if(i==1){ printf("Input ERROR!\n"); exit(10); } break; } //.txt file case 1:{ char filename[64]; char test; printf("Please enter file name: (excluding extension)\nFile must be organized in a column of floating point numbers!\n"); fgets(filename, 60, stdin); fflush(stdin); if(strlen(filename)>60){ printf("ERROR: Filename too long! Please keep file name shorter than 60 characters!\n"); exit(110); } //removing newline from filename for(i=0; i<60; i++){ if(filename[i]=='\n' || filename[i]=='\r'){ filename[i] = '.'; filename[i+1] = '\0'; break; } } strcat(filename, "txt"); FILE* f = fopen(filename, "r"); if(!f){ printf("ERROR: Could not open %s file!", filename); exit(111); } fseek(f, 0, SEEK_END); i = ftell(f); fseek(f, 0, SEEK_SET); if(i==0){ printf("ERROR: File %s is empty!", filename); exit(112); } //get number of lines in file k = 0; do{ test= getc(f); if(test == '\n'){ k++; num = 1; }else if(test!=EOF){ num = 0; } }while(test!=EOF); fseek(f, 0, SEEK_SET); if(num == 0){ k++; } //read data data = (double*)realloc(data, k*sizeof(double)); for(i=0; i<k-1; i++){ fscanf(f, "%lf\n", &data[i]); } if(num == 0){ fscanf(f, "%lf", &data[k-1]); } else{ fscanf(f, "%lf\n", &data[k-1]); } fclose(f); break; } //.bin file case 2:{ char filename[64]; printf("Please enter file name: (excluding extension)\nFile must be organized in long doubles!\n"); fgets(filename, 60, stdin); fflush(stdin); if(strlen(filename)>60){ printf("ERROR: Filename too long! Please keep file name shorter than 60 characters!\n"); exit(120); } //removing newline from filename for(i=0; i<60; i++){ if(filename[i]=='\n' || filename[i]=='\r'){ filename[i] = '.'; filename[i+1] = '\0'; break; } } strcat(filename, "bin"); FILE* f = fopen(filename, "rb"); if(!f){ printf("ERROR: Could not open %s file!", filename); exit(121); } fseek(f, 0, SEEK_END); i = ftell(f); fseek(f, 0, SEEK_SET); if(i==0){ printf("ERROR: File %s is empty!", filename); exit(122); } //read data k = i/sizeof(double); data = (double*)realloc(data, k*sizeof(double)); fread(data, sizeof(double), k, f); fclose(f); break; } default:{ printf("ERROR: Invalid input!"); exit(13); } } qsort((void*)data, k, sizeof(double), (int (*)(const void*, const void*))sortiranje); printf("Median is: median(x)="); if(k%2==0) x_med = (data[k/2-1]+data[k/2])/2; else x_med = data[k/2]; printf("%le\n", x_med); sum = 0; printf("Sample mean is: avg(x)="); for(i=0; i<k; i++) { sum += data[i]; } x_avg = sum/k; printf("%le\n", x_avg); sum = 0; del_x = fabs(data[0]-x_avg); printf("Standard deviation is: m="); for(i=0; i<k; i++) { sum += (data[i]-x_avg)*(data[i]-x_avg); if(del_x*del_x < (data[i]-x_avg)*(data[i]-x_avg)) del_x = fabs(data[i]-x_avg); } m = sqrt(sum/(k-1)); printf("%e\n", m); printf("Greatest deviation from mean is: delta_x=%le\n", del_x); printf("Variance is: M="); M = m/sqrt(k); printf("%le\n", M); printf("Result: x = %le +- %le\n", x_avg, M); printf("Coefficient of variation is: R="); R = M/x_avg; printf("%lf%%\n", R*100); free(data); break; } //Statistics of results case 2:{ long int i=0, k=0; double x_avg=0, M_avg=0, R=0; double sum=0; dataset* data = (dataset*)malloc(0); printf("Do you want to read data from a file?\n1-Yes .txt file\n2-Yes .bin file\n0-No\n"); scanf("%hhu", &num); fflush(stdin); switch(num){ //Manual input case 0:{ i==1; printf("Insert sample vector: (you end by inserting non-number)\nFormat: x, Mx\n"); data = (dataset*)realloc(data, sizeof(dataset)); printf("x[%lu], M[%lu] = ", k+1, k+1); while(scanf("%lf, %lf", &data[k].data1, &data[k].data2)==2) { fflush(stdin); k++; i=0; data = (dataset*)realloc(data, sizeof(dataset)*(k+1)); printf("x[%lu], M[%lu] = ", k+1, k+1); } fflush(stdin); data = (dataset*)realloc(data, sizeof(dataset)*k); if(i==1){ printf("Input ERROR!\n"); exit(20); } break; } //.txt file case 1:{ char filename[64]; char test; printf("Please enter file name: (excluding extension)\nFile must be organized in a column of x, Mx!\n"); fgets(filename, 60, stdin); fflush(stdin); if(strlen(filename)>60){ printf("ERROR: Filename too long! Please keep file name shorter than 60 characters!\n"); exit(210); } //removing newline from filename for(i=0; i<60; i++){ if(filename[i]=='\n' || filename[i]=='\r'){ filename[i] = '.'; filename[i+1] = '\0'; break; } } strcat(filename, "txt"); FILE* f = fopen(filename, "r"); if(!f){ printf("ERROR: Could not open %s file!", filename); exit(211); } fseek(f, 0, SEEK_END); i = ftell(f); fseek(f, 0, SEEK_SET); if(i==0){ printf("ERROR: File %s is empty!", filename); exit(212); } //get number of lines in file k = 0; do{ test= getc(f); if(test == '\n'){ k++; num = 1; }else if(test!=EOF){ num = 0; } }while(test!=EOF); fseek(f, 0, SEEK_SET); if(num == 0){ k++; } //read data data = (dataset*)realloc(data, k*sizeof(dataset)); for(i=0; i<k-1; i++){ fscanf(f, "%lf, %lf\n", &data[i].data1, &data[i].data2); } if(num == 0){ fscanf(f, "%lf, %lf", &data[k-1].data1, &data[k-1].data2); } else{ fscanf(f, "%lf, %lf\n", &data[k-1].data1, &data[k-1].data2); } fclose(f); break; } //.bin file case 2:{ char filename[64]; printf("Please enter file name: (excluding extension)\nFile must be organized in 2 long doubles!\n"); fgets(filename, 60, stdin); fflush(stdin); if(strlen(filename)>60){ printf("ERROR: Filename too long! Please keep file name shorter than 60 characters!\n"); exit(220); } //removing newline from filename for(i=0; i<60; i++){ if(filename[i]=='\n' || filename[i]=='\r'){ filename[i] = '.'; filename[i+1] = '\0'; break; } } strcat(filename, "bin"); FILE* f = fopen(filename, "rb"); if(!f){ printf("ERROR: Could not open %s file!", filename); exit(221); } fseek(f, 0, SEEK_END); i = ftell(f); fseek(f, 0, SEEK_SET); if(i==0){ printf("ERROR: File %s is empty!", filename); exit(222); } //read data k = i/sizeof(dataset); data = (dataset*)realloc(data, k*sizeof(dataset)); fread(data, sizeof(dataset), k, f); fclose(f); break; } default:{ printf("ERROR: Invalid input!"); exit(23); } } printf("General variance is: avg(M)="); sum = 0; for(i=0; i<k; i++) sum += 1/(data[i].data2*data[i].data2); M_avg = sqrt(1/sum); printf("%le\n", M_avg); printf("General mean is: avg(m)="); sum = 0; for(i=0; i<k; i++) sum += data[i].data1/(data[i].data2*data[i].data2); x_avg = sum*M_avg*M_avg; printf("%le\n", x_avg); printf("General result: x = %le +- %le\n", x_avg, M_avg); R = M_avg/x_avg; printf("General coefficient of variation is: %lf%%\n", R*100); free(data); break; } //Linear regression case 3:{ long int i=0, k=0, del=0, difi=0; double sumx=0, sumy=0, sumxy=0, sumx2=0, sumy2=0; double a, b, Ma, Mb, R; double sum=0, diff=0; dataset* data = (dataset*)malloc(0); dataset* removed = (dataset*)malloc(0); double* r = (double*)malloc(0); printf("Do you want to read data from a file?\n1-Yes .txt file\n2-Yes .bin file\n0-No\n"); scanf("%hhu", &num); fflush(stdin); switch(num){ //Manual input case 0:{ i==1; printf("Insert sample vector: (you end by inserting non-number)\nFormat: x, y\n"); data = (dataset*)realloc(data, sizeof(dataset)); printf("x[%lu], y[%lu]=", k+1, k+1); while(scanf("%lf, %lf", &data[k].data1, &data[k].data2)==2) { fflush(stdin); k++; i=0; data = (dataset*)realloc(data, sizeof(dataset)*(k+1)); printf("x[%lu], y[%lu]=", k+1, k+1); } fflush(stdin); data = (dataset*)realloc(data, sizeof(dataset)*k); if(i==1){ printf("Input ERROR!\n"); exit(30); } break; } //.txt file case 1:{ char filename[64]; char test; printf("Please enter file name: (excluding extension)\nFile must be organized in a column of x, y!\n"); fgets(filename, 60, stdin); fflush(stdin); if(strlen(filename)>60){ printf("ERROR: Filename too long! Please keep file name shorter than 60 characters!\n"); exit(310); } //removing newline from filename for(i=0; i<60; i++){ if(filename[i]=='\n' || filename[i]=='\r'){ filename[i] = '.'; filename[i+1] = '\0'; break; } } strcat(filename, "txt"); FILE* f = fopen(filename, "r"); if(!f){ printf("ERROR: Could not open %s file!", filename); exit(311); } fseek(f, 0, SEEK_END); i = ftell(f); fseek(f, 0, SEEK_SET); if(i==0){ printf("ERROR: File %s is empty!", filename); exit(312); } //get number of lines in file k = 0; do{ test= getc(f); if(test == '\n'){ k++; num = 1; }else if(test!=EOF){ num = 0; } }while(test!=EOF); fseek(f, 0, SEEK_SET); if(num == 0){ k++; } //read data data = (dataset*)realloc(data, k*sizeof(dataset)); for(i=0; i<k-1; i++){ fscanf(f, "%lf, %lf\n", &data[i].data1, &data[i].data2); } if(num == 0){ fscanf(f, "%lf, %lf", &data[k-1].data1, &data[k-1].data2); } else{ fscanf(f, "%lf, %lf\n", &data[k-1].data1, &data[k-1].data2); } fclose(f); break; } //.bin file case 2:{ char filename[64]; printf("Please enter file name: (excluding extension)\nFile must be organized in 2 long doubles!\n"); fgets(filename, 60, stdin); fflush(stdin); if(strlen(filename)>60){ printf("ERROR: Filename too long! Please keep file name shorter than 60 characters!\n"); exit(320); } //removing newline from filename for(i=0; i<60; i++){ if(filename[i]=='\n' || filename[i]=='\r'){ filename[i] = '.'; filename[i+1] = '\0'; break; } } strcat(filename, "bin"); FILE* f = fopen(filename, "rb"); if(!f){ printf("ERROR: Could not open %s file!", filename); exit(321); } fseek(f, 0, SEEK_END); i = ftell(f); fseek(f, 0, SEEK_SET); if(i==0){ printf("ERROR: File %s is empty!", filename); exit(322); } //read data k = i/sizeof(dataset); data = (dataset*)realloc(data, k*sizeof(dataset)); fread(data, sizeof(dataset), k, f); fclose(f); break; } default:{ printf("ERROR: Invalid input!"); exit(33); } } printf("What is proposed linear relationship?\n0 ... x - y\n1 ... ln x - y\n2 ... x - ln y\n3 ... ln x - ln y\n"); scanf("%hhu", &num); fflush(stdin); //automatic linearization switch(num){ // x - y case 0:{ break; } // lnx - y case 1:{ for(i=0; i<k; i++){ data[i].data1 = log(data[i].data1); } break; } // x - lny case 2:{ for(i=0; i<k; i++){ data[i].data2 = log(data[i].data2); } break; } // lnx - lny case 3:{ for(i=0; i<k; i++){ data[i].data1 = log(data[i].data1); data[i].data2 = log(data[i].data2); } break; } default:{ printf("ERROR: Invalid input!"); exit(34); } } CALC: r = (double*)realloc(NULL, k*sizeof(double)); sumx=0; sumy=0; sumxy=0; sumx2=0; sumy2=0; for(i=0; i<k; i++){ sumx += data[i].data1; sumy += data[i].data2; sumxy += data[i].data1*data[i].data2; sumx2 += data[i].data1*data[i].data1; sumy2 += data[i].data2*data[i].data2; } a = (k*sumxy-sumx*sumy)/(k*sumx2-sumx*sumx); b = (sumy-a*sumx)/k; Ma = sqrt((k*sumy2-sumy*sumy-a*a*(k*sumx2-sumx*sumx))/((k-2)*(k*sumx2-sumx*sumx))); Mb = Ma*sqrt(sumx2/k); sum = 0; for(i=0; i<k; i++){ r[i] = data[i].data2 - a*data[i].data1 - b; sum += r[i]*r[i]; } R = sqrt(sum); sum = 0; for(i=0; i<k; i++){ sum += data[i].data2*data[i].data2; } R /= sqrt(sum); if(del==0){ printf("Do you want to skip automatic removal of bad points?\n1-Yes\n0-No\n"); scanf("%hhu", &num2); printf("%hhu\n", num); fflush(stdin); if(num2!=1 && num2!=0){ printf("ERROR: Invalid input!\n"); exit(333); } } //Whether line is good enough aproximation (ie. is there a bad point) if(R>=(1-sqrt(0.9)) && num2==0){ del++; removed = (dataset*)realloc(removed, sizeof(dataset)*del); diff = r[0]; difi = 0; for(i=1; i<k; i++){ if(diff*diff<r[i]*r[i]){ diff=r[i]; difi=i; } } removed[del-1].data1 = data[difi].data1; removed[del-1].data2 = data[difi].data2; //removal long long int temp=0; for(i=0; i<k; i++) { if(i!=difi){ data[temp].data1 = data[i].data1; data[temp].data2 = data[i].data2; temp++; } } data[k-1].data1 = 0; data[k-1].data2 = 0; k--; data = (dataset*)realloc(data, sizeof(dataset)*k); goto CALC; } free(r); printf("Slope: a = %le +- %le\n", a, Ma); printf("Y-intercept: b = %le +- %le\n", b, Mb); printf("Slope-intercept form: y = %le x + %le\n", a, b); printf("Variance from line: r=%lf%%\n", R*100); printf("Points removed from calculations:"); if(del==0) printf(" none\n"); else{ printf("\n"); for(i=0; i<del; i++){ printf("[%lf, %lf]\n", removed[i].data1, removed[i].data2); } } //Regrouping of data and removed data data = (dataset*)realloc(data, sizeof(dataset)*(k+del)); for(i=k; i<k+del; i++){ data[i].data1 = removed[i-k].data1; data[i].data2 = removed[i-k].data2; } k+=del; free(removed); //Plotting part double xmin, xmax, ymin, ymax, cmin, cmax, ymin2, ymax2, cmin2, cmax2; double xs[k]; double ys[k]; for(i=0; i<k; i++){ xs[i] = data[i].data1; ys[i] = data[i].data2; } free(data); xmin = min(xs, k); xmax = max(xs, k); ymin = min(ys, k); ymax = max(ys, k); cmin = xmin - 0.1*(xmax-xmin); //canvas x min cmax = xmax + 0.1*(xmax-xmin); //canvas x max ymin2 = a*cmin + b; ymax2 = a*cmax + b; if(ymin<ymin2){ cmin2 = ymin; }else{ cmin2 = ymin2; } if(ymax>ymax2){ cmax2 = ymax; }else{ cmax2 = ymax2; } double xs2[] = {cmin, cmax}; double ys2[] = {ymin2, ymax2}; ScatterPlotSeries *series = GetDefaultScatterPlotSeriesSettings(); series->xs = xs; series->xsLength = sizeof(xs)/sizeof(double); series->ys = ys; series->ysLength = sizeof(ys)/sizeof(double); series->linearInterpolation = false; series->pointType = L"dots"; series->pointTypeLength = wcslen(series->pointType); series->color = CreateRGBColor(1, 0, 0); ScatterPlotSeries *series2 = GetDefaultScatterPlotSeriesSettings(); series2->xs = xs2; series2->xsLength = sizeof(xs2)/sizeof(double); series2->ys = ys2; series2->ysLength = sizeof(ys2)/sizeof(double); series2->linearInterpolation = true; series2->lineThickness = 1.0; series2->color = CreateRGBColor(0, 0, 1); ScatterPlotSettings *settings = GetDefaultScatterPlotSettings(); settings->width = 1920; settings->height = 1080; settings->autoBoundaries = false; settings->xMin = cmin; settings->xMax = cmax; settings->yMin = cmin2; settings->yMax = cmax2; settings->autoPadding = true; //getting axis names switch(num){ // x - y case 0:{ settings->xLabel = L"Y"; settings->yLabel = L"X"; break; } // lnx - y case 1:{ settings->xLabel = L"Y"; settings->yLabel = L"lnX"; break; } // x - lny case 2:{ settings->xLabel = L"lnY"; settings->yLabel = L"X"; break; } // lnx - lny case 3:{ settings->xLabel = L"lnY"; settings->yLabel = L"lnX"; break; } } settings->title = L"Linear regression y(x)"; settings->titleLength = wcslen(settings->title); settings->xLabelLength = wcslen(settings->xLabel); settings->yLabelLength = wcslen(settings->yLabel); ScatterPlotSeries *s [] = {series, series2}; settings->scatterPlotSeries = s; settings->scatterPlotSeriesLength = 2; RGBABitmapImageReference *canvasReference = CreateRGBABitmapImageReference(); DrawScatterPlotFromSettings(canvasReference, settings); size_t length; double *pngdata = ConvertToPNG(&length, canvasReference->image); WriteToFile(pngdata, length, "regression_plot.png"); DeleteImage(canvasReference->image); free(series); free(series2); free(settings); free(pngdata); free(canvasReference); break; } default: { printf("ERROR: Invalid input!\n"); exit(4); } } //whether to redo printf("Do you want to redo?\n1-Yes\n0-No\n"); fflush(stdin); scanf("%hhu", &num); fflush(stdin); if(num==1) goto START; return 0; }
C
/* * @file OSAL_Semaphore.c * @brief * @author * @version 0.1.0 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <semaphore.h> #include "OSAL_Memory.h" #include "OSAL_Semaphore.h" #undef JETOMX_LOG_TAG #define JETOMX_LOG_TAG "JETOMX_LOG_SEMA" #define JETOMX_LOG_OFF #define JETOMX_TRACE_ON #include "OSAL_Log.h" OMX_ERRORTYPE OSAL_SemaphoreCreate(OMX_HANDLETYPE *semaphoreHandle) { sem_t *sema; sema = (sem_t *)OSAL_Malloc(sizeof(sem_t)); if (!sema) return OMX_ErrorInsufficientResources; if (sem_init(sema, 0, 0) != 0) { OSAL_Free(sema); return OMX_ErrorUndefined; } *semaphoreHandle = (OMX_HANDLETYPE)sema; return OMX_ErrorNone; } OMX_ERRORTYPE OSAL_SemaphoreTerminate(OMX_HANDLETYPE semaphoreHandle) { sem_t *sema = (sem_t *)semaphoreHandle; if (sema == NULL) return OMX_ErrorBadParameter; if (sem_destroy(sema) != 0) return OMX_ErrorUndefined; OSAL_Free(sema); return OMX_ErrorNone; } OMX_ERRORTYPE OSAL_SemaphoreWait(OMX_HANDLETYPE semaphoreHandle) { sem_t *sema = (sem_t *)semaphoreHandle; FunctionIn(); if (sema == NULL) return OMX_ErrorBadParameter; if (sem_wait(sema) != 0) return OMX_ErrorUndefined; FunctionOut(); return OMX_ErrorNone; } OMX_ERRORTYPE OSAL_SemaphorePost(OMX_HANDLETYPE semaphoreHandle) { sem_t *sema = (sem_t *)semaphoreHandle; FunctionIn(); if (sema == NULL) return OMX_ErrorBadParameter; if (sem_post(sema) != 0) return OMX_ErrorUndefined; FunctionOut(); return OMX_ErrorNone; } OMX_ERRORTYPE OSAL_Set_SemaphoreCount(OMX_HANDLETYPE semaphoreHandle, OMX_S32 val) { sem_t *sema = (sem_t *)semaphoreHandle; if (sema == NULL) return OMX_ErrorBadParameter; if (sem_init(sema, 0, val) != 0) return OMX_ErrorUndefined; return OMX_ErrorNone; } OMX_ERRORTYPE OSAL_Get_SemaphoreCount(OMX_HANDLETYPE semaphoreHandle, OMX_S32 *val) { sem_t *sema = (sem_t *)semaphoreHandle; int semaVal = 0; if (sema == NULL) return OMX_ErrorBadParameter; if (sem_getvalue(sema, &semaVal) != 0) return OMX_ErrorUndefined; *val = (OMX_S32)semaVal; return OMX_ErrorNone; }
C
#include<stdio.h> #include<string.h> int count = 0; int n,x,y; int flag = 0; int starting = 0, xpassed = 0; int dfs(int start, int end, int adj[n][n], int visited[n]) { if(visited[start] != 0) { return 0; } if(start == x) xpassed = 1; if(start == y && xpassed == 1) { xpassed = 0; return 0; } visited[start] = 1; count++; //printf("in node : %d\n",start); if(start == end) { printf("dist b/w %d and %d is : %d\n",starting,end,count-1); flag = 1; return 0; } for(int i=0;i<n && flag==0;i++) { if(adj[start][i] > 0 && i!=starting && visited[i] == 0) { dfs(i,end,adj,visited); } } count--; xpassed = 0; } int main() { scanf(" %d %d %d",&n,&x,&y); x--;y--; int adj[n][n]; memset(adj, 0, sizeof(adj)); for(int i=0;i<n-1;i++) { int a,b; scanf(" %d %d",&a,&b); a--;b--; adj[a][b] = 1; adj[b][a] = 1; } int visited[n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { //printf("for node %d %d\n",i,j); memset(visited, 0, sizeof(visited)); count = 0; xpassed = 0; flag = 0; starting = i; if(j!=i) dfs(i,j,adj,visited); } } return 0; }