language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
//
// Created by xyc on 18-2-2.
//
#include "unp.h"
static ssize_t readn(int fd,void *any,size_t n);
static ssize_t readn(int fd,void *any,size_t n)
{
char *ptr;
size_t nleft;
ssize_t read_n;
nleft = n;
ptr = (char *)any;
while (nleft > 0) {
if((read_n = read(fd,ptr,nleft)) < 0) {
/* if interrupt */
if (errno == EINTR) {
continue;
} else {
return -1;
}
/* read EOF */
} else if(read_n == 0) {
break;
} else {
nleft -= read_n;
ptr += read_n;
}
}
return (n - nleft);
}
ssize_t Readn(int fd, void *any, size_t n)
{
ssize_t read_n;
if ((read_n = readn(fd,any,n)) < 0) {
err_sys("readn error");
}
return read_n;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#define STRING_TO_HASH "This is a test string. Lorem ipsum and stuff."
#define HASH_VALUE 0x40f1e9
void __declspec(dllexport) Lab4a()
{
char buf[MAX_PATH+1] = {0};
size_t value = 0;
char* tmp = NULL;
tmp = STRING_TO_HASH;
if(strlen(tmp) == 0)
return;
for(; *tmp != '\0'; ++tmp)
value = (unsigned short)*tmp + 31 * value;
_snprintf(buf, sizeof(buf), "%s", STRING_TO_HASH);
printf("%s : 0x%x\n", buf, value);
}
int __cdecl main(int argc, char* argv[], char* envp[])
{
Lab4a();
return 0;
}
|
C
|
#ifndef HEADER_H
# define HEADER_H
/*--------------------------------
!! required structure
--------------------------------*/
struct s_node {
int value;
struct s_node *right;
struct s_node *left;
};
/*--------------------------------
:) function you must implement
--------------------------------*/
struct s_node *createBST(int *arr, int n);
/*--------------------------------
?? test function used in main
--------------------------------*/
void printBinaryTree(struct s_node * t); //print a binary tree
/*--------------------------------
& your own other function
--------------------------------*/
struct s_node *init_node(int value);
void add_node(struct s_node **root, int value);
#endif
|
C
|
//
// main.c
// test_4_22
//
// Created by hh on 2020/4/22.
// Copyright © 2020 Yeee. All rights reserved.
//
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <ctype.h>
//int main(int argc, const char * argv[]) {
// // insert code here...
// printf("Hello, World!\n");
// return 0;
//}
//#define SwapInitbit(n) (( (n) & 0x55555555 << 1) | ((n) & 0xaaaaaaaa >> 1))
//void main()
//{
// int a = 0;
// int b = 0;
// scanf("%d", &a);
// printf("%d ", a);
// b = SwapInitbit(a);
// printf("%d ", b);
//}
//#define EXCHANGE(n) (((n)&0x55555555)<<1)|(((n)&0xaaaaaaaa)>>1)
//
//int main()
//{
// int n = 0;
// int m = 0;
// scanf("%d", &n);
// printf("交换前:%d\n", n);
// m = EXCHANGE(n);
// printf("交换后:%d\n", m);
//
// return 0;
//}
//#define offsetof(SturctType, MemberName) (size_t) & (SturctType -> MenmberName)
//enum State
//{
// VALID,
// INVALID
//};
//enum State state = INVALID;
//
//int my_atoi(char *str)
//{
// int flag = 1;
// long long ret = 0;
// assert(str);
// state = INVALID;
// while(isspace(*str))
// {
// str++;
// }
// if(*str == '\0')
// {
// return 0;
// }
// if(*str == '+')
// {
// str++;
// }
// if(*str == '-')
// {
// flag = -1;
// str++;
// }
// while(isdight(*str))
// {
// ret = ret * 10 + flag * (*str - '0');
// if((ret > INT_MAX) || (ret < INT_MAX))
// {
// return 0;
// }
// str++;
// }
// if(*str == '0')
// {
// state = VALID;
// return(int)ret;
// }
// else
// {
// return(int)ret;
// }
//}
//void main()
//{
// char *p = "1234hjk0987";
// if(state == VALID)
// printf("%d\n ", my_atoi(p));
//
//}
//char* mystrncat(char* dst, const char* src, size_t n)
//{
// assert(NULL != dst && NULL != src);
// char* tmp = dst;
// while(*dst)
// {
// dst++;
// }
// int i = 0;
// for(i = 0; src[i] && i < n; i++)
// {
// dst[i] = src[i];
// }
// dst[i] = 0;
// return tmp;
//}
//
//void main()
//{
// char str1[] = "asdfghjkl";
// char str2[] = "qwertyui";
// printf("%s\n", mystrncat(str1, str2, 6));
//
//}
//char* mystrncpy(char* dst, const char* src, size_t n)
//{
// assert(NULL != dst && NULL != src);
// int i = 0;
// for(i = 0; src[i] && i < n; i++)
// {
// dst[i] = src[i];
// }
// if(i < n)
// {
// dst[i] = 0;
// }
// return dst;
//}
//void main()
//{
// char str1[] = "asdfgh";
// char str2[] = "zxcvbn";
// printf("%s\n", mystrncpy(str1, str2, 5));
//}
void findTwoNum(int arr[], int sz, int num1, int num2)
{
int i = 0;
int sum = 0;
for(i = 0; i < 9; i++)
{
sum ^= arr[i];
}
int pos = 0;
for(i = 0; i < 32; i++)
{
if(sum & 1 << i)
{
pos = i;
break;
}
}
num1 = num2 = 0;
for(i = 0; i < 10 ; i++)
{
if(arr[i] & 1 << pos)
{
num1 ^= arr[i];
}
else
{
num2 ^= arr[i];
}
}
}
void main()
{
int arr[] = {1, 2, 4, 5, 7, 8, 9, 10 ,4, 1};
int sz = sizeof(arr) / sizeof(arr[0]);
int num1 = 0;
int num2 = 0;
findTwoNum(arr, sz, &num1, &num2);
printf("num1 = %d,num2 = %d\n", num1, num2);
}
|
C
|
/* Copyright (c) 2016, Tejas Kokje. All rights reserved
* Use of this source code is governed by a Simplified BSD
* license that can be found in the LICENSE file.*/
#include "donmap.h"
/* This function is the starting of worker thread function
* for doing TCP port scan using conect()*/
void *donmap_tcp_connect_worker(void *args)
{
int sockfd, flags, n, error, working_port = 0;
socklen_t len;
struct timeval tval;
struct addrinfo hints, *servinfo, *p;
int rv, i;
char port_str[6];
fd_set wset;
donmap_thread_cfg_t *thread_cfg;
FD_ZERO(&wset);
thread_cfg = (donmap_thread_cfg_t *) args;
if (thread_cfg == NULL) {
fprintf(stderr, "%s() Invalid argument\n", __FUNCTION__);
return NULL;
}
/* Walk through all the ports assigned to this thread.
* thread_cfg->port will tell us which ports we should
* scan. thread_cfg->port + 1 is the first port to scan*/
for (i = 1; i <= gbl_cfg.num_ports_per_thread; i++) {
working_port = thread_cfg->port + i;
if (working_port > NUM_PORTS
|| working_port > gbl_cfg.end_port || thread_error) {
break;
}
/*Resolve hostname first*/
memset(&hints, 0, sizeof hints);
if (gbl_cfg.use_ipv6) {
hints.ai_family = AF_INET6;
} else {
hints.ai_family = AF_INET;
}
hints.ai_socktype = SOCK_STREAM;
snprintf(port_str, 6, "%d", working_port);
if ((rv = getaddrinfo(thread_cfg->hostname, port_str, &hints, &servinfo)) != 0) {
pthread_mutex_lock(&thread_lock);
if (!thread_error) {
fprintf(stderr, "\nFailed to resolve or route %s\n", thread_cfg->hostname);
fflush(stderr);
}
thread_error = 1;
pthread_mutex_unlock(&thread_lock);
return NULL;
}
// loop through all the results and connect to the first we can
for (p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) < 0) {
pthread_mutex_lock(&thread_lock);
if (!thread_error) {
fprintf(stderr,
"\nFailed to open socket for %s port %d - %s\n",
thread_cfg->hostname, working_port, strerror(errno));
}
thread_error = 1;
pthread_mutex_unlock(&thread_lock);
return NULL;
}
/* Set socket to non blocking. We will use select() to catch response*/
flags = fcntl(sockfd, F_GETFL, 0);
fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
if ((n = connect(sockfd, p->ai_addr, p->ai_addrlen)) < 0) {
if (errno != EINPROGRESS) {
close(sockfd);
pthread_mutex_lock(&thread_lock);
if (!thread_error) {
fprintf(stderr,
"\nFailed to connect for %s port %d - %s\n",
thread_cfg->hostname, working_port, strerror(errno));
}
thread_error = 1;
pthread_mutex_unlock(&thread_lock);
return NULL;
}
}
if (n == 0) {
/* Connected immediately*/
BITSET(port_map, working_port);
BITSET(completed_port_map, working_port);
break;
}
FD_ZERO(&wset);
FD_SET(sockfd, &wset);
break;
}
if (p) {
sel:
tval.tv_sec = 0;
tval.tv_usec = gbl_cfg.timeout;
if ((n = select(sockfd + 1, NULL, &wset, NULL, &tval)) == 0) {
errno = ETIMEDOUT;
BITSET(completed_port_map, working_port);
close(sockfd);
continue;
}
if (errno == EINTR) {
goto sel;
}
if (FD_ISSET(sockfd, &wset)) {
len = sizeof(error);
if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, &len)< 0) {
close(sockfd);
BITSET(completed_port_map, working_port);
continue;
} else {
if (!error) {
/* Connected to remote port. Set the bit in port_map
* indicating success*/
BITSET(port_map, working_port);
}
}
} else {
fprintf(stderr, "\nselect() error. sockfd is not set\n");
}
} else {
pthread_mutex_lock(&thread_lock);
if (!thread_error) {
fprintf(stderr,
"\nFailed to connect for %s port %d - %s\n",
thread_cfg->hostname, working_port, strerror(errno));
}
thread_error = 1;
pthread_mutex_unlock(&thread_lock);
return NULL;
}
close(sockfd);
BITSET(completed_port_map, working_port);
}
return NULL;
}
void *donmap_progress_worker(void *args)
{
sleep(1);
memset(out_buff, 32, 150);
out_buff[0] = '\r';
out_buff[1] = '[';
out_buff[103] = ']';
out_buff[108] = '\0';
snprintf(out_buff + 104, 5, "%d%%", 0);
fprintf(stdout, "%s", out_buff);
fflush(stdout);
char toggleChar = ' ';
int prevPercent = 0, currPercent = 0;
while (1) {
int i, completedCount = 0;
for (i = 1; i < NUM_PORTS; i++) {
if (BITTEST(completed_port_map, i)) {
completedCount++;
}
}
currPercent = (int) ((completedCount * 100) / (gbl_cfg.end_port - gbl_cfg.start_port + 1));
if (currPercent <= 100 && currPercent > prevPercent) {
memset(out_buff + 2 + prevPercent, '#', currPercent - prevPercent);
snprintf(out_buff + 104, 5, "%d%%", currPercent);
fprintf(stdout, "%s", out_buff);
fflush(stdout);
prevPercent = currPercent;
} else {
out_buff[currPercent + 2] = toggleChar;
fprintf(stdout, "%s", out_buff);
fflush(stdout);
toggleChar = (toggleChar == ' ' ? '#' : ' ');
}
sleep(1);
}
return NULL;
}
|
C
|
/*
* Tree Sort Operations
* By: Liam P. Walsh
* Tree uses AVL method (Balances after append and remove)
*/
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define size 10
// Declares tree node struct.
typedef struct tree_node_ {
// Data of tree node
int number;
// Pointers to nodes
struct tree_node_ * right;
struct tree_node_ * left;
struct tree_node_ * parent;
} tree_node;
// Declares tree struct. (hold root)
typedef struct tree_ {
// The root node of the tree
tree_node * root;
} tree;
// Allocates node with the given data, and returns address.
tree_node * create_node(int number) {
// Allocate data for node, setting values to NULL/0.
tree_node * node = calloc(1, sizeof(tree_node));
// Set the node's data
node->number = number;
return node;
}
// Allocates tree with the given root, and returns address.
tree * create_list() {
// Allocate list.
tree * tree_struct = calloc(1, sizeof(tree));
return tree_struct;
}
// Recursively frees nodes called by the node pointer.
void free_node(tree_node * node, tree * list) {
if (!node) {
return;
}
// Recursively calls to the end of the list.
if (node->left) {
free_node(node->left, list);
}
if (node->right) {
free_node(node->right, list);
}
// Frees nodes, starting from the end of the list.
free(node);
}
// Frees nodes and sets head to NULL.
int empty_list(tree * list) {
// Verify there's a list
if (!list) {
return 0;
}
// Free any nodes attached to the list.
if (list->root) {
free_node(list->root, list);
}
// Empties list by setting to NULL.
list->root = NULL;
return 1;
}
// Counts the furthest level of child nodes.
int count_level(tree_node * root) {
// Makes sure there is a node.
if (!root) {
return 0;
}
// Finds the end of the list, and returns count.
int cL = count_level(root->left);
int cR = count_level(root->right);
if (cL > cR) {
return cL + 1;
}
return cR + 1;
}
// Swap/Rotate nodes
tree_node * swap_node(tree_node * root, int left) {
// Makes sure there is a list and node.
tree_node * tmp = root;
if (root && left) {
if (root->left->right)
{
root->left = swap_node(root->left, 0);
}
tmp = root->left;
tmp->parent = root->parent;
root->parent = tmp;
root->left = tmp->right;
tmp->right = root;
}
else if (root && !left) {
if (root->right->left)
{
root->right = swap_node(root->right, 1);
}
tmp = root->right;
tmp->parent = root->parent;
root->parent = tmp;
root->right = tmp->left;
tmp->left = root;
}
return tmp;
}
// Recursively balances nodes by checking the node's left and right levels.
void balance_sub_tree(tree_node * parent, tree_node * node, int left_node) {
// Makes sure there is a list and node to append.
if (!node || !parent) {
return;
}
// Checks balance of tree, and swaps if needed.
int left = 0;
int right = 0;
balance_sub_tree(node, node->left, 1);
balance_sub_tree(node, node->right, 0);
left = count_level(node->left);
right = count_level(node->right);
while (left+1 < right || right+1 < left) {
if (left+1 < right) {
node = swap_node(node, 0);
}
else {
node = swap_node(node, 1);
}
if (left_node) {
parent->left = node;
}
else {
parent->right = node;
}
left = count_level(node->left);
right = count_level(node->right);
}
}
// Balances tree by calling balance_sub_tree, and swap_node.
void balance_tree(tree * list) {
// Makes sure there is a list and node to append.
if (!list || !list->root) {
return;
}
// Checks balance of tree, and swaps if needed.
int left = 0;
int right = 0;
balance_sub_tree(list->root, list->root->left, 1);
balance_sub_tree(list->root, list->root->right, 0);
left = count_level(list->root->left);
right = count_level(list->root->right);
while (left+1 < right || right+1 < left) {
if (left+1 < right) {
list->root = swap_node(list->root, 0);
}
else {
list->root = swap_node(list->root, 1);
}
left = count_level(list->root->left);
right = count_level(list->root->right);
}
}
// Append node to front of list. (Replaces head node)
int append_node(tree_node * new, tree * list) {
// Makes sure there is a list and node to append.
if (!list || !new) {
return 0;
}
// If the list is empty, sets the node as root.
if (!list->root) {
list->root = new;
}
// Finds the end of the list, and appends to the end.
else {
tree_node * iter = list->root;
int left = 1;
while (iter) {
if (new->number <= iter->number) {
new->parent = iter;
iter = iter->left;
left = 1;
}
else {
new->parent = iter;
iter = iter->right;
left = 0;
}
}
iter = new->parent;
if (left) {
iter->left = new;
}
else {
iter->right = new;
}
}
balance_tree(list);
return 1;
}
// Parses list and prints node data.
int sub_tree_fill(tree_node * node, int tree_array[], int i) {
if (!node) {
return 0;
}
if (node->left) {
i = sub_tree_fill(node->left, tree_array, i);
}
tree_array[i++] = node->number;
if (node->right) {
i = sub_tree_fill(node->right, tree_array, i);
}
return i;
}
// Heap Sort - Max Heap notation
void sort_list(int tree_array[], tree * tree_list) {
// Verify there's a list
if (!tree_list || !tree_array) {
return;
}
sub_tree_fill(tree_list->root, tree_array, 0);
}
// Fills list with random numbers.
int fill_lists(int list[], tree * tree_list) {
srand(time(0));
// Verify there's a list
if (!list) {
return 0;
}
for (int i = 0; i < size; ++i ) {
list[i] = rand()%100;
append_node(create_node(list[i]), tree_list);
}
return 1;
}
// Prints the array list.
void print_array(int list[]) {
printf("Printing list: ");
if (!list) {
printf("No list\n");
return;
}
for (int i = 0; i < size; ++i ) {
printf("%d ", list[i]);
}
printf("\n");
}
int main()
{
printf("Unsorted Array:\n");
tree * tree_list = create_list();
int tree_array[size] = {0};
fill_lists(tree_array, tree_list);
print_array(tree_array);
sort_list(tree_array, tree_list);
empty_list(tree_list);
free(tree_list);
printf("Sorted Array:\n");
print_array(tree_array);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define VEC_SIZE 3
#define SWAP(a,b,t) t=a;a=b;b=t;
unsigned long long int min_lattice_vector(long long int * a, long long int * b);
unsigned long long int lin_comb_mag(long long int * a, long long int * b, long long int c, long long int d);
void lin_comb(long long int * dest, long long int * a, long long int * b, long long int c, long long int d);
unsigned long long int l1_norm(long long int * a);
long long int line_search(long long int * a, long long int * b,unsigned long long int a_norm);
void swap(long long int * a, long long int * b, int size);
void print_vec(long long int * v, int size);
void print_vec(long long int * v, int size)
{
int i;
printf("[");
for (i = 0; i < size; i++)
{
printf("%lld ",v[i]);
}
printf("]\n");
}
void swap(long long int * a, long long int * b, int size)
{
long long int temp = 0;
for (int i = 0; i <= size; i++) {
temp = a[i];
a[i] = b[i];
b[i] = temp;
}
}
//negate a
void negate(long long int * a);
void negate(long long int * a)
{
for (int i = 0; i < VEC_SIZE; i++) {
a[i] = -a[i];
}
}
int main()
{
long long int * V, * W,* past_trib, * curr_trib,*tmp;
unsigned long long int mod = 10000000;
unsigned long long int num_blocks = 20000000;
unsigned long long int checkpoint = 100000;
unsigned long long int sum = 0;
int block_size = 12;
V = (long long int *)malloc(VEC_SIZE*sizeof(long long int));
if (!V) {printf("Memory Error"); exit(1);}
W = (long long int *)malloc(VEC_SIZE*sizeof(long long int));
if (!W) {printf("Memory Error"); exit(1);}
curr_trib = (long long int *)malloc(block_size*sizeof(long long int));
if (!curr_trib) {printf("Memory Error"); exit(1);}
past_trib = (long long int *)malloc(block_size*sizeof(long long int));
if (!past_trib) {printf("Memory Error"); exit(1);}
past_trib[block_size-1] = 0;
past_trib[block_size-2] = 1;
past_trib[block_size-3] = -1;
for (int i = 0; i < num_blocks; i++)
{
curr_trib[0] = (past_trib[block_size-1] + past_trib[block_size-2] + past_trib[block_size-3]) % mod;
curr_trib[1] = (curr_trib[0] + past_trib[block_size-1] + past_trib[block_size-2]) % mod;
curr_trib[2] = (curr_trib[1] + curr_trib[0] + past_trib[block_size-1]) % mod;
for (int j = 3; j < block_size; j++) {
curr_trib[j] = (curr_trib[j-1] + curr_trib[j-2] + curr_trib[j-3] ) % mod;
}
V[0] = curr_trib[0] - curr_trib[1];
V[1] = curr_trib[2] + curr_trib[3];
V[2] = curr_trib[4]*curr_trib[5];
W[0] = curr_trib[6] - curr_trib[7];
W[1] = curr_trib[8] + curr_trib[9];
W[2] = curr_trib[10]*curr_trib[11];
sum += min_lattice_vector(W, V);
if ((i + 1) % checkpoint == 0) {
printf("On S(%d), current sum %llu\n",i+1,sum);
}
SWAP(curr_trib,past_trib,tmp)
}
printf("FINAL SUM: %llu\n",sum);
}
unsigned long long int min_lattice_vector(long long int * a, long long int * b)
{
unsigned long long int a_norm, b_norm, temp, a_minus_b, a_plus_b;
long long int k = 0;
long long int * t;
a_norm = l1_norm(a);
b_norm = l1_norm(b);
//ensure a has greater norm
if (a_norm < b_norm) {
SWAP(a_norm,b_norm,temp)
SWAP(a,b,t)
}
a_minus_b = lin_comb_mag(a,b,1,-1); // = |a-b|
a_plus_b = lin_comb_mag(a,b,1,1); // = |a+b|
if (a_minus_b < b_norm) {
lin_comb(b,a,b,1,-1); // b = a - b
SWAP(a_minus_b,b_norm,temp)
}
if (a_minus_b >= a_norm) {
if (a_plus_b >= a_norm) // already reduced
{
// printf("Already Reduced\n");
return b_norm;
}
else if (a_plus_b < b_norm) {
negate(a); // a = -a, swapping |a + b| and |a - b|
SWAP(a_minus_b,a_plus_b,temp)
lin_comb(b,a,b,1,-1); // b = a - b
SWAP(a_minus_b,b_norm,temp)
// printf("NOT well-ordered, case 1\n");
}
else {
negate(a); // a = -a, swapping |a + b| and |a - b|
SWAP(a_minus_b,a_plus_b,temp)
// printf("NOT well-ordered, case 2\n");
}
}
while (a_norm > a_minus_b)
{
k = line_search(a,b,a_norm);
lin_comb(a,a,b,1,k); // a = a + k*b
a_minus_b = lin_comb_mag(a,b,1,-1); // = |a-b|
a_plus_b = lin_comb_mag(a,b,1,1); // = |a+b|
if (a_plus_b < a_minus_b)
{
negate(a);
SWAP(a_plus_b, a_minus_b,temp)
}
a_norm = l1_norm(a);
if (b_norm > a_norm)
{
SWAP(a,b,t)
SWAP(a_norm,b_norm,temp)
}
}
unsigned long long int max_norm, min_norm;
b_norm = l1_norm(b);
if (a_norm > b_norm)
{
max_norm = a_norm;
min_norm = b_norm;
}
else
{
max_norm = b_norm;
min_norm = a_norm;
}
if (a_minus_b < max_norm || a_plus_b < max_norm) {
printf("ERROR. Conditions of theorem not satisfied. Results inaccurate.\n");
printf("|a-b| = %llu, |a+b| = %llu, |a| = %llu, |b| = %llu\n",a_minus_b, a_plus_b,a_norm,b_norm);
print_vec(a,VEC_SIZE);
print_vec(b,VEC_SIZE);
}
return min_norm;
}
unsigned long long int lin_comb_mag(long long int * a, long long int * b, long long int c, long long int d)
{
unsigned long long int res = 0;
for (int i = 0; i < VEC_SIZE; i++) {
long long int temp = c*a[i] + d*b[i];
if (temp > 0) res += (temp);
else res += -temp;
}
return res;
}
void lin_comb(long long int * dest, long long int * a, long long int * b, long long int c, long long int d)
{
for (int i = 0; i < VEC_SIZE; i++) {
dest[i] = c*a[i] + d*b[i];
}
}
unsigned long long int l1_norm(long long int * a)
{
unsigned long long int res = 0;
for (int i = 0; i < VEC_SIZE; i++) {
if (a[i] > 0) res += a[i];
else res += -a[i];
}
return res;
}
long long int line_search(long long int * a, long long int * b,unsigned long long int a_norm)
{
long long int k_min = 0;
unsigned long long int min = a_norm;
unsigned long long int temp = 0;
long long int k_temp = 0;
for (int i = 0; i < VEC_SIZE; i++) {
if (b[i]) {
k_temp = -a[i]/b[i];
temp = lin_comb_mag(a,b,1,k_temp);
if (temp < a_norm) {
min = temp;
k_min = k_temp;
}
k_temp = -a[i]/b[i] - 1;
temp = lin_comb_mag(a,b,1,k_temp);
if (temp < a_norm) {
min = temp;
k_min = k_temp;
}
}
}
return k_min;
}
|
C
|
// Author: Saptarshi Das
// Date: 19/02/2021
/*
Take as number as input and if the square of the number end with the number itself, then output "Correct Number", else output
"Incorrect Number", if the user enters negative integer the result should display "Wrong Input".
Input Format:
Contains an integer 'N' denoting the number
Output Format:
*/
#include<stdio.h>
#include<math.h>
void check_square_end(int n)
{
int n_square, count_digit = 0, temp = n,ten_pow;
// find the number of digits in n
while(temp>0)
{
temp = temp/10;
count_digit++;
}
n_square = pow(n,2);
// raise 10 to the power of the digits in n
ten_pow = pow(10,count_digit);
if(n<0)
printf("Wrong Input");
// divide by the number obtained by raising the 10th power of the count_digits
else if(n_square%ten_pow == n)
printf("Correct Number");
else
printf("Incorrect Number");
}
int main()
{
int n;
scanf("%d",&n);
check_square_end(n);
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
main()
{
//Variables
int numero;
int contador;
//Inicializacion
numero=0;
contador=1;
//Programa
//Bucle Do While
printf("Bucle Do While\n");
printf("Introduzca un numero:\n");
scanf("%d",&numero);
do
{
if (numero>0)
{
printf("%d\n",contador);
contador++;
}
else
{
printf("%d\n",contador);
contador--;
}
}
while(contador!=numero);
}
|
C
|
# include <stdlib.h>
# include <stdio.h>
# include <math.h>
# include "amg_matrix.h"
# include "amg_list.h"
# include "../../../Allocation_Operations/allocations.h"
matrix * create_m (int m, int n, int nnz) {
matrix *A = (matrix *) mycalloc("A of create_m",1,sizeof(matrix));
A->m = m; A->n = n; A->nnz = nnz;
A->val = (double *) mycalloc("A->val of create_m",nnz,sizeof(double));
A->diag = (double *) mycalloc("A->diag of create_m", n, sizeof(double));
A->col_ind = (int *) mycalloc("A->col_ind of create_m",nnz,sizeof(int));
A->row_ptr = (int *) mycalloc("A->row_ptr of create_m",(m+1),sizeof(int));
return A;
};
matrix * copy_m(matrix * A) {
matrix * B = create_m(A->n, A->m, A->nnz);
int i;
B->m = A->m;
B->n = A->n;
B->nnz = A->nnz;
for(i=0; i<A->nnz; i++) {
B->val[i] = A->val[i];
B->col_ind[i] = A->col_ind[i];
}
for(i=0; i<A->n; i++)
B->diag[i] = A->diag[i];
for(i=0; i<(A->m+1); i++)
B->row_ptr[i] = A->row_ptr[i];
return B;
}
void destroy_m (matrix *A) {
myfree(A->val); myfree(A->diag);
myfree(A->col_ind); myfree(A->row_ptr);
myfree(A);
};
void print_m (matrix *A) {
int i, j, n=A->m;
for (i=0; i<n; i++) {
printf("%d:", i+1);
for (j=A->row_ptr[i]; j<A->row_ptr[i+1]; j++) printf(" %.6f (%d);", A->val[j], A->col_ind[j]+1);
printf("\n");
}
};
double get_Aij (matrix *A, int i, int j) {
int k;
for (k=A->row_ptr[i]; k<A->row_ptr[i+1]; k++) {
if (A->col_ind[k] == j) return A->val[k];
}
return 0.0;
};
matrix * csr_transpose (matrix *A) {
int i, j, m=A->m, n=A->n;
matrix *A_t;
Node *aux;
list **row_elem = (list **) mycalloc("row_elem of csr_transpose",n,sizeof(list *));
for (i=0; i<n; i++) row_elem[i] = create_l();
for (i=0; i<m; i++) {
for (j=A->row_ptr[i]; j<A->row_ptr[i+1]; j++) insert_l_tail(row_elem[A->col_ind[j]], i, A->val[j]);
}
A_t = create_m(n, m, A->nnz);
for (A_t->row_ptr[0]=0, j=0, i=0; i<A_t->m; i++) {
for (aux=row_elem[i]->head; aux; aux=aux->next, j++) {
A_t->val[j] = aux->val;
A_t->col_ind[j] = aux->elem;
}
A_t->diag[i] = A->diag[i];
A_t->row_ptr[i+1] = j;
}
for (i=0; i<n; i++) destroy_l(row_elem[i]);
myfree(row_elem);
return A_t;
};
matrix * sum(matrix *A, matrix *A_t) {
matrix *A_s;
Node *aux;
int i, j, j_t, nnz=0;
list **row_elem = (list **) mycalloc("row_elem of sum",A->n,sizeof(list *));
for (i=0; i<A->n; i++) row_elem[i] = create_l();
for (i=0; i<A->n; i++)
{
j = A-> row_ptr[i+1]-1;
j_t = A_t-> row_ptr[i+1]-1;
while((j >= A->row_ptr[i]) || (j_t >= A_t->row_ptr[i])) { /*se esta na linha*/
if((j >= A->row_ptr[i]) && (j_t >= A_t->row_ptr[i]) &&
(A->col_ind[j] == A_t->col_ind[j_t])) {
insert_l_head(row_elem[i], A->col_ind[j], A->val[j] + A_t->val[j_t]); //fabs(A->val[j]) + fabs(A_t->val[j_t]));
j--;
j_t--;
} else
if(((j >= A->row_ptr[i]) &&
(A->col_ind[j] > A_t->col_ind[j_t])) ||
(j_t < A_t->row_ptr[i])) {
insert_l_head(row_elem[i], A->col_ind[j], A->val[j]); //fabs(A->val[j]));
j--;
} else
{
insert_l_head(row_elem[i], A_t->col_ind[j_t], A_t->val[j_t]); //fabs(A_t->val[j_t]));
j_t--;
}
nnz++;
}
}
A_s = create_m(A->n, A->m, nnz);
for (A_s->row_ptr[0]=0, j=0, i=0; i<A_s->m; i++) {
for (aux=row_elem[i]->head; aux; aux=aux->next, j++) {
A_s->val[j] = aux->val;
A_s->col_ind[j] = aux->elem;
}
//A_s->diag[i] = 0; //nao precisa devido ao calloc
A_s->row_ptr[i+1] = j;
}
for (i=0; i<A->n; i++) destroy_l(row_elem[i]);
myfree(row_elem);
return A_s;
}
matrix * sum_abs(matrix *A, matrix *A_t) {
matrix *A_s;
Node *aux;
int i, j, j_t, nnz=0;
list **row_elem = (list **) mycalloc("row_elem of sum_abs",A->n,sizeof(list *));
for (i=0; i<A->n; i++) row_elem[i] = create_l();
for (i=0; i<A->n; i++)
{
j = A-> row_ptr[i+1]-1;
j_t = A_t-> row_ptr[i+1]-1;
while((j >= A->row_ptr[i]) || (j_t >= A_t->row_ptr[i])) { /*se esta na linha*/
if((j >= A->row_ptr[i]) && (j_t >= A_t->row_ptr[i]) &&
(A->col_ind[j] == A_t->col_ind[j_t])) {
insert_l_head(row_elem[i], A->col_ind[j], fabs(A->val[j]) + fabs(A_t->val[j_t]));
j--;
j_t--;
} else
if(((j >= A->row_ptr[i]) &&
(A->col_ind[j] > A_t->col_ind[j_t])) ||
(j_t < A_t->row_ptr[i])) {
insert_l_head(row_elem[i], A->col_ind[j], fabs(A->val[j]));
j--;
} else
{
insert_l_head(row_elem[i], A_t->col_ind[j_t], fabs(A_t->val[j_t]));
j_t--;
}
nnz++;
}
}
A_s = create_m(A->n, A->m, nnz);
for (A_s->row_ptr[0]=0, j=0, i=0; i<A_s->m; i++) {
for (aux=row_elem[i]->head; aux; aux=aux->next, j++) {
A_s->val[j] = aux->val;
A_s->col_ind[j] = aux->elem;
}
//A_s->diag[i] = 0; //nao precisa devido ao calloc
A_s->row_ptr[i+1] = j;
}
for (i=0; i<A->n; i++) destroy_l(row_elem[i]);
myfree(row_elem);
return A_s;
}
matrix * sum_upper(matrix *A, matrix *A_t) {
matrix *A_s;
Node *aux;
int i, j, j_t, nnz=0;
list **row_elem = (list **) mycalloc("row_elem of sum_upper",A->n,sizeof(list *));
for (i=0; i<A->n; i++) row_elem[i] = create_l();
for (i=0; i<A->n; i++)
{
j = A-> row_ptr[i+1]-1;
j_t = A_t-> row_ptr[i+1]-1;
while(((j >= A->row_ptr[i]) || (j_t >= A_t->row_ptr[i])) && /*se esta na linha*/
((A->col_ind[j] > i) || (A_t->col_ind[j_t] > i))) { /*se esta na triangular superior*/
if(A->col_ind[j] == A_t->col_ind[j_t]) {
insert_l_head(row_elem[i], A->col_ind[j], fabs(A->val[j]) + fabs(A_t->val[j_t]));
j--;
j_t--;
} else
if(A->col_ind[j] > A_t->col_ind[j_t]) {
insert_l_head(row_elem[i], A->col_ind[j], fabs(A->val[j]));
j--;
} else
{
insert_l_head(row_elem[i], A_t->col_ind[j_t], fabs(A_t->val[j_t]));
j_t--;
}
nnz++;
}
}
A_s = create_m(A->n, A->m, nnz);
for (A_s->row_ptr[0]=0, j=0, i=0; i<A_s->m; i++) {
for (aux=row_elem[i]->head; aux; aux=aux->next, j++) {
A_s->val[j] = aux->val;
A_s->col_ind[j] = aux->elem;
}
//A_s->diag[i] = 0; //nao precisa devido ao calloc
A_s->row_ptr[i+1] = j;
}
for (i=0; i<A->n; i++) destroy_l(row_elem[i]);
myfree(row_elem);
return A_s;
}
double maxCoeff_abs (matrix *A) {
int i, j, n=A->m;
double max = 0.0;
for (i=0; i<n; i++) {
for (j=A->row_ptr[i]; j<A->row_ptr[i+1]; j++) { if (fabs(A->val[j])>max) max = fabs(A->val[j]); }
}
return max;
};
matrix * matmat_sparseproduct (matrix *A, matrix *B) {
int *xb, p=A->m, r=B->n, ip, i, jp, j, kp, k;
double *x;
matrix *C;
Node *aux;
list **row_elem = (list **) mycalloc("row_elem of matmat_sparseproduct",p,sizeof(list *));
xb = (int *) mycalloc("xb of matmat_sparseproduct",r, sizeof(int));
x = (double *) mycalloc("x of matmat_sparseproduct",r,sizeof(double));
ip = 0;
for (i=0; i<p; i++) { // each iteration fills a row in matrix C
row_elem[i] = create_l();
for (jp=A->row_ptr[i]; jp<A->row_ptr[i+1]; jp++) {
j = A->col_ind[jp];
for (kp=B->row_ptr[j]; kp<B->row_ptr[j+1]; kp++) {
k = B->col_ind[kp];
if (xb[k]!=i+1) {
insert_l_tail(row_elem[i], k, 0.0);
ip++;
xb[k] = i+1;
x[k] = A->val[jp]*B->val[kp];
} else x[k] += A->val[jp]*B->val[kp];
}
}
for (aux=row_elem[i]->head; aux; aux=aux->next) aux->val = x[aux->elem];
}
myfree(xb); myfree(x);
C = create_m(p, r, ip);
for (C->row_ptr[0]=0, j=0, i=0; i<p; i++) {
for (aux=row_elem[i]->head; aux; aux=aux->next, j++) {
C->val[j] = aux->val;
C->col_ind[j] = aux->elem; if (aux->elem==i) C->diag[i] = aux->val;
}
C->row_ptr[i+1] = j;
}
for (i=0; i<p; i++) destroy_l(row_elem[i]);
myfree(row_elem);
return C;
};
void mat_vec (double *p, matrix *A, double *v) {
int i, j, n=A->m;
for (i=0; i<n; i++) {
p[i] = 0.0;
for (j=A->row_ptr[i]; j<A->row_ptr[i+1]; j++) p[i] += A->val[j]*v[A->col_ind[j]];
}
};
void mat_vec_plus (double *p, matrix *A, double *v) {
int i, j, n=A->m;
for (i=0; i<n; i++) {
for (j=A->row_ptr[i]; j<A->row_ptr[i+1]; j++) p[i] += A->val[j]*v[A->col_ind[j]];
}
};
|
C
|
// жǷ
#include <stdio.h>
int main() {
int x,i;
int judge = 1;
printf("жǷ,룺");
scanf_s("%d", &x);
for (i = 2; i < x; i++) {
if (x % i == 0) {
judge = 0;
break;
}
}
if (judge == 1) {
printf("%d!",x);
}
else {
printf("%d!",x);
}
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int c=0,d=0,g1,g2,g=0,i=0,G=0,e=0,X1;
while(1)
{
scanf("%d %d",&g1, &g2);
if(g1>g2)
{
i++;
}
if(g1<g2)
{
G++;
}
if(g1==g2)
{
e++;
}
c+=g1;
d+=g2;
g++;
printf("novo calculo (1-sim 2-nao)\n");
scanf("%d",&X1);
if(X1==1)
{
continue;
}
if(X1==2)
{
break;
}
}
printf("%d grenais\n",g);
printf("Inter:%d\n",i);
printf("Gremio:%d\n",G);
printf("Empates:%d\n",e);
if(i>G)
{
printf("Inter venceu mais\n");
}
if(i<G)
{
printf("Gremio venceu mais\n");
}
if(i==G)
{
printf("Nao houve vencedor\n");
}
return 0;
}
|
C
|
/* This program is designed so that the user enters their age and
the program tells them how many times there heart has beated since birth.
Author: Robert Eviston
Date: 7th October 2013
*/
#include <stdio.h>
main()
{
int age;
long total_beats;
printf("Please enter your age to find out how many beats your heart has made: ");
scanf("%d", &age);
flushall();
total_beats = 39446175 * age;
printf("Your heart has beated %d times in your %d years of life", total_beats, age);
getchar();
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bsausage <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/09/20 12:38:43 by bsausage #+# #+# */
/* Updated: 2019/09/20 12:38:44 by bsausage ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
#include <stdio.h>
static int read_from_str(char **line, char **str)
{
size_t i;
char *tmp;
i = ft_strchr(*str, '\n') - *str;
(*str)[i] = '\0';
if (!(*line = ft_strdup(*str)))
return (-1);
if (!(tmp = ft_strdup(&(*str)[i + 1])))
return (-1);
free(*str);
if (!(*str = ft_strdup(tmp)))
return (-1);
free(tmp);
return (1);
}
static char *add_buff(int fd, char **str, int *ret)
{
char buf[BUFF_SIZE + 1];
char *tmp;
*ret = read(fd, buf, BUFF_SIZE);
buf[*ret] = '\0';
tmp = ft_strdup(*str);
free(*str);
*str = ft_strjoin(tmp, buf);
free(tmp);
return (*str);
}
int get_last_line(char **line, t_struct **current)
{
t_struct *tmp;
if (!(*line = ft_strdup((*current)->str)))
return (-1);
free((*current)->str);
tmp = (*current)->next;
free(*current);
*current = tmp;
return (1);
}
static t_struct *find_fd(t_struct *begin_list, int fd)
{
t_struct *list;
list = begin_list;
while (list)
{
if (list->fd == fd)
return (list);
list = list->next;
}
if (!(list = (t_struct*)malloc(sizeof(t_struct))))
return (NULL);
list->fd = fd;
list->str = NULL;
list->next = NULL;
return (list);
}
int get_next_line(const int fd, char **line)
{
int ret;
static t_struct *begin_list;
t_struct *current;
ret = 1;
if (!line || fd < 0 || BUFF_SIZE < 1 || read(fd, NULL, 0) < 0)
return (-1);
if (!begin_list)
{
if (!(begin_list = (t_struct*)malloc(sizeof(t_struct))))
return (-1);
begin_list->fd = fd;
begin_list->str = NULL;
begin_list->next = NULL;
}
if (!(current = find_fd(begin_list, fd)))
return (-1);
while (ret > 0)
{
if (!(current->str))
current->str = ft_strnew(0);
if (ft_strchr(current->str, '\n'))
return (read_from_str(line, &(current->str)));
if (!(current->str = add_buff(fd, &(current->str), &ret)))
return (-1);
}
if (!ret && ft_strlen(current->str))
return (get_last_line(line, ¤t));
return (0);
}
|
C
|
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_FILE_BUFFER_SIZE 128
#define TOKENS_SIZE 48
#define STRING_BUFFER_SIZE 128
#define STRING_BUFFER_LIMIT 127
#define IS_SPACE(c) (c < '!')
#define IS_ALPHA(c) (('A' <= c) && (c <= 'z'))
typedef uint8_t u8;
typedef enum {
EMPTY = 0,
SPACE,
WORD,
OTHER,
} token_type_t;
typedef struct {
token_type_t type;
char* string;
} token_t;
typedef struct {
token_t items[TOKENS_SIZE];
char strings[STRING_BUFFER_SIZE];
} tokens_t;
typedef struct {
char buffer[MAX_FILE_BUFFER_SIZE];
tokens_t tokens;
} memory_t;
static void set_buffer(char* buffer, FILE* file) {
fseek(file, 0, SEEK_END);
size_t size = (size_t)ftell(file);
if (MAX_FILE_BUFFER_SIZE <= size) {
exit(EXIT_FAILURE);
}
rewind(file);
if (fread(buffer, sizeof(char), size, file) != size) {
exit(EXIT_FAILURE);
}
buffer[size] = '\0';
}
#define INCREMENT_BUFFER c = buffer[++i_b]
#define SET_POINTER tokens->items[i_t].string = &tokens->strings[i_s]
#define SET_CHAR(c) tokens->strings[i_s++] = c
#define SET_TYPE(t) tokens->items[i_t++].type = t
#define EXIT_IF_STRING_BUFFER_OVERFLOW \
if (STRING_BUFFER_LIMIT <= i_s) { \
exit(EXIT_FAILURE); \
}
static void set_tokens(tokens_t* tokens, const char* buffer) {
u8 i_b = 0;
u8 i_t = 0;
u8 i_s = 0;
for (char c = buffer[i_b]; c != '\0';) {
if (TOKENS_SIZE == i_t) {
exit(EXIT_FAILURE);
}
if (IS_SPACE(c)) {
if ((i_b == 0) || (!IS_SPACE(buffer[i_b - 1]))) {
SET_TYPE(SPACE);
}
INCREMENT_BUFFER;
} else if (IS_ALPHA(c)) {
/* NOTE: There must be room for the next character *and* '\0'! */
EXIT_IF_STRING_BUFFER_OVERFLOW;
SET_POINTER;
SET_TYPE(WORD);
SET_CHAR(c);
INCREMENT_BUFFER;
while (IS_ALPHA(c)) {
EXIT_IF_STRING_BUFFER_OVERFLOW;
SET_CHAR(c);
INCREMENT_BUFFER;
}
SET_CHAR('\0');
} else {
EXIT_IF_STRING_BUFFER_OVERFLOW;
SET_POINTER;
SET_TYPE(OTHER);
SET_CHAR(c);
SET_CHAR('\0');
INCREMENT_BUFFER;
}
}
for (; i_t < TOKENS_SIZE; ++i_t) {
tokens->items[i_t].type = EMPTY;
}
}
#undef INCREMENT_BUFFER
#undef SET_POINTER
#undef SET_CHAR
#undef SET_TYPE
#undef EXIT_IF_STRING_BUFFER_OVERFLOW
int main(int argv, char** argc) {
if (argv == 1) {
return EXIT_FAILURE;
}
FILE* file = fopen(argc[1], "r");
if (file == NULL) {
return EXIT_FAILURE;
}
memory_t* memory = malloc(sizeof(memory_t));
if (memory == NULL) {
return EXIT_FAILURE;
}
char* buffer = memory->buffer;
tokens_t* tokens = &memory->tokens;
set_buffer(buffer, file);
set_tokens(tokens, buffer);
for (u8 i = 0; i < TOKENS_SIZE; ++i) {
token_t* token = &tokens->items[i];
switch (token->type) {
case EMPTY: {
printf("(%2u) _\n", i);
break;
}
case SPACE: {
printf("(%2u) SPACE\n", i);
break;
}
case WORD: {
printf("(%2u) WORD : \"%s\"\n", i, token->string);
break;
}
case OTHER: {
printf("(%2u) OTHER : \"%s\"\n", i, token->string);
break;
}
}
}
fclose(file);
free(memory);
return EXIT_SUCCESS;
}
|
C
|
/*
* @file main.c
* @brief Solution for the second PES project
*
* This is a C program which blinks LED in 4 different targets:
* frdm_release
* frdm_debug
* pc_release
* pc_debug
*
* The debug targets log the led status and colour, as well as the
current
* time and elapsed time since the last LED transition
*
* The release targets outputs only the LED colour
*
* The outputs of the PC targets can be viewed on the terminal,
and the
* outputs of the FRDM targets can be viewed on the KL25Z
*
* This code implements the touch sensor and the RTC as well *
* All the targets are compiled using a single main function * and a single makefile
*
* @author Rahul Ramaprasad, Prayag Milan Desai
* @date October 3 2019
* @version 1.0
*/
/* Including library file for IO functions */
#include <stdio.h>
/* Include the header file that contains common function declarations */
#include "common_pc_frdm.h"
/* These header files will be included only for frdm_release target */
#ifdef frdm_release
#include "../frdm_includes/frdmReleaseHeader.h"
#endif
/* These header files will be included only for frdm_debug target */
#ifdef frdm_debug
#include "../frdm_includes/frdmDebugHeader.h"
#include <time.h>
#endif
/* These header files will be included only for pc_release target */
#if defined pc_release || defined pc_debug
#include "../pc_includes/common_pc.h"
#endif
/* Defining clock variables of time.h library for calculating elapsed time in pc_debug */
#ifdef pc_debug
clock_t startElapseTimer;
clock_t stopElapseTimer;
#endif
/* Defining extern variables from Touch_Sensor.h to check the Touch slider input */
#if defined frdm_debug || defined frdm_release
int checkColor;
bool checkTouchSlider;
#endif
/* Main function definition */
int main(void) {
/* Run the initialization function to initialise the pins and
hardware */
#if defined frdm_debug || defined frdm_release
init_pins();
poll();
#endif
#ifdef frdm_debug
rtc_init();
currentEpoch = epoch;
#endif
/* Check if the touch slider was sensed and ledindex is not
equal to a LED off operaton index */
for ( LUTindex = 0; LUTindex < 20; LUTindex++, ledIndex++)
{
#if defined frdm_debug || defined frdm_release
if ( checkTouchSlider == true && ledIndex != 1 && ledIndex != 3 && ledIndex != 5)
{
/* Switch off all LEDs before turning on the LED
due to touch slider interrupt */
LED_RED_OFF();
LED_GREEN_OFF();
LED_BLUE_OFF();
/* checkColor stores the ledIndex to turn on the
respective LED */
ledIndex = checkColor;
/* Change the value of the bool variable to false
to check for next touch slider interrupt */
checkTouchSlider = false;
}
#endif
#ifdef pc_debug
/* Print the Elapsed time since last instruction by
subtracting clock ticks and dividing by the clock frequency*/
printf("%.3f ", ((double)(stopElapseTimer - startElapseTimer) / CLOCKS_PER_SEC) * 1000);
/* Start the elapse timer clock */
startElapseTimer = clock();
#endif
/* Check if ledIndex reaches 6 and set it to 0 so it can
start blinking from RED */
if (ledIndex >= 6) ledIndex = 0;
setLed(ledIndex);
delay(lookUpTable[LUTindex]);
/* Start the stop elapse timer clock to check the elapsed time in the begining of the next iteration of the loop */
#ifdef pc_debug
stopElapseTimer = clock();
#endif
}
return 0 ;
}
|
C
|
#include <stdio.h>
#include "list.h"
#include "node.h"
#include <stdlib.h>
const int kSLListError = -1;
//
CharList *SLCreateList()
{
//
CharList *theList = (CharList *)malloc(sizeof(CharList));
//
theList->head = NULL;
theList->tail = NULL;
theList->count = 0;// cont=0
return theList;
}
void SLFreeList(CharList *aList)
{
//
if (NULL == aList)
return;
CharNode *theNode = aList->head;
//
do
{
CharNode *theNodeToBeFree = theNode;
theNode = theNode->nextNode;
SLFreeCharNode(theNodeToBeFree);
}while (NULL != theNode);
free(aList);
}
CharNode * SLAddNode(CharList *aList, CharNode *aNewNode)
{
//
if (NULL == aList || NULL == aNewNode)
{
return NULL;
}
//
if (NULL == aList->head && NULL == aList->tail)
{
//
aList->head = aList->tail = aNewNode;
}
else
{
CharNode *theTail = aList->tail;
aList->tail = aNewNode;
if (NULL != theTail)
{
theTail->nextNode = aList->tail;
}
}
aList->count += 1;
return aNewNode;
}
int SLCountList(const CharList *aList)
{
int theResult = kSLListError;
if (NULL != aList)
{
theResult = aList->count;
}
return theResult;
}
CharNode *SLNodeAtIndex(const CharList *aList, int anIndex)
{
CharNode *theResult = NULL;
if (NULL != aList && anIndex < aList->count)
{
int i = 0;
CharNode *theNode = aList->head;
do
{
if (i == anIndex)
{
theResult = theNode;
break;
}
i++;
theNode = theNode->nextNode;//
} while (NULL != theNode);
}
return theResult;
}
void SLSwapNodesByIndex(CharList *aList, int theLeft, int theRight)
{
if (theLeft == theRight) return ;
CharNode *theNode_l = SLNodeAtIndex(aList,theLeft);
CharNode *theNode_r = SLNodeAtIndex(aList,theRight);
int theTmp = theNode_l->size;
theNode_l->size = theNode_r->size;
theNode_r->size = theTmp;
char Tmpchar[7];
for(int i = 0; i < theNode_r->size; i++){
Tmpchar[i] = theNode_l->words[i];
theNode_l->words[i] = theNode_r->words[i];
theNode_r->words[i] = Tmpchar[i];
}
}
int partitionIt(CharList *aList, int aLeftIndex, int aRightIndex, int aPivot)
{
int theLeft = aLeftIndex - 1;
int theRight = aRightIndex + 1;
while (1)
{
// search the bigest element
while (theLeft < aRightIndex && SLNodeAtIndex(aList, ++theLeft)->size < aPivot);
// search the lowest element
while (theRight > aLeftIndex && SLNodeAtIndex(aList,--theRight)->size > aPivot);
if (theLeft = theRight) // pointer are the same
{
break;
}
else
{
//lets to swap elements
SLSwapNodesByIndex(aList, theLeft, theRight);
}
}
return theLeft; // return break position
}
void quickSort(CharList *aList, int aLeftIndex, int aRightIndex)
{
if (aRightIndex <= aLeftIndex)
{
return; //the array is fully sorted
}
int thePivot = SLNodeAtIndex(aList, aRightIndex)->size;
int thePartitionIndex = partitionIt(aList, aLeftIndex, aRightIndex, thePivot);
//left part sorting
quickSort(aList, aLeftIndex, thePartitionIndex - 1);
//right part sorting
quickSort(aList, thePartitionIndex + 1, aRightIndex);
}
|
C
|
#include <TFile.h>
#include <TH2D.h>
#include <TH1D.h>
#include <TTree.h>
#include <algorithm>
#include <vector>
void centralityDetermination(){
TFile *glauberFile = new TFile("../glauber_PbPb_default_v1p5_10k.root","read");
TTree *tree = (TTree*)glauberFile->Get("nt_Pb_Pb");
TH1D *hNpart = new TH1D("hNpart","Number of Participants Distribution;Npart;Counts",500,-0.5,499.5);
TH2D *hNpartB = new TH2D("hNpartB","Npart vs b; b; Npart",200,0,20.0,500,0,500);
Float_t Npart, Ncoll, B;
tree->SetBranchAddress("Npart", &Npart);
tree->SetBranchAddress("Ncoll", &Ncoll);
tree->SetBranchAddress("B", &B);
const int nBins = 10;
double binBoundaries[nBins+1];
vector<float> impactParameters;
Int_t nEvent = tree->GetEntries();
for(int i=0; i<nEvent; i++){
if(i%1000==0) cout<<"Have run "<<i<<" out of "<<nEvent<<" events; "<<endl;
tree->GetEntry(i);
hNpart->Fill(Npart);
hNpartB->Fill(B, Npart);
impactParameters.push_back(B);
}
sort(impactParameters.begin(),impactParameters.end());
int size = impactParameters.size();
binBoundaries[nBins] = impactParameters[size-1]+0.1;
cout <<endl << "Impact parameter boundaries for each centrality range:"<<endl;
for(int i = 0; i < nBins; i++) {
int entry = (int)(i*(size/nBins));
if(entry < 0 || i == 0) binBoundaries[i] = 0;
else binBoundaries[i] = impactParameters[entry];
cout << binBoundaries[i] << ", ";
}
cout << binBoundaries[nBins] << endl << endl;
TH1D *hCentrality = new TH1D("hCentrality","Number of Event in each Centrality bin;Centrality;Counts",nBins,0,100);
cout<<"Event loop 2, to fill centrality histogram"<<endl;
for(int i=0; i<nEvent; i++){
if(i%1000==0) cout<<"Have run "<<i<<" out of "<<nEvent<<" events in the Event loop 2;"<<endl;
tree->GetEntry(i);
for(int j = 0; j < nBins; j++){
if(B>=binBoundaries[j] && B<binBoundaries[j+1])
hCentrality->Fill(j*100/nBins);
}
}
cout<<endl<<"Bin Number of events"<<endl;
for(int i = 0; i < nBins; i++) {
cout<<i<<" "<<hCentrality->GetBinContent(i+1)<<endl;
}
cout<<endl<<endl;
hCentrality->SetMinimum(0);
hCentrality->Draw();
//cout<<"<Npart> = "<<hNpart->GetMean()<<endl;
//cout<<"# of entries = "<<hNpartB->GetEntries()<<endl;
}
|
C
|
#ifndef GEOMETRY_H
#define GEOMETRY_H
#include "dl_list.h"
#include "utilsmath.h"
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#ifdef debug
#include <stdio.h>
#endif
typedef void (*RASTER_FUNC_2D)(int32_t const * const x, int32_t const * const y, void *data);
typedef void (*RASTER_BEZIER_FUNC_2D)(vec2_t const * const p1, vec2_t const * const p2, void *data);
vec2_t** geometry_convex_hull(vec2_t *points, size_t cnt_points);
void geometry_line(vec2_t *start, vec2_t *end, RASTER_FUNC_2D rFunc, void *data);
void geometry_circle(vec2_t *center, int32_t *radius, RASTER_FUNC_2D rFunc, void *data);
void geometry_ellipse(vec2_t *center, int32_t *_a, int32_t *_b, RASTER_FUNC_2D rFunc, void *data);
/**
* functions goes throught vec3 array and will calculate triangles in an simple way.
* the list are containing vec3 instances for triangles. Every 3 vecs a trinagle ends
* as sequence of t1p1,t1p2,t1p3,t2p1,t2p2,t2p3,...
* t1 = triangle 1
* t2 = triangle 2
* t1p1 = triangle 1 point 1 ....
*/
dl_list_t * geometry_triangulate(const vec3_t *vecs, size_t cnt_vecs);
void geometry_bezier1(vec2_t *start, vec2_t *cp, vec2_t *end, uint32_t *steps, RASTER_BEZIER_FUNC_2D rFunc, void *data);
void geometry_bezier2(vec2_t *start, vec2_t *cp1, vec2_t *cp2, vec2_t *end, uint32_t *steps, RASTER_BEZIER_FUNC_2D rFunc, void *data);
#endif
|
C
|
#include <stdio.h>
void main()
{
/*enum empl{nm=5,acc=65,age};
enum empl x,y,z,*p;
clrscr();
x=nm;
y=acc;
z=age;
p=&z;
printf("X=%d\tY=%d\tZ=%d\tP(z)=%u",x,y,z,*p);*/
/*int x=28,y,z;
clrscr(); */
printf("%d");
//printf("X=%d\tY=%d\tZ=%d");
getch();
}
|
C
|
/*
File name : compiler.c
Vers : 0.01a
Written by : Setiadi Rachmat
Date : Fri Aug 28 10:08:03 WIT 2009
Modified by : Sadan Fitroni
*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include "scanner.h"
#include "compiler.h"
extern token_t token;
void program(void);
void statement(void);
int main(int argc,char *argv[])
{
init_token("example.txt");
program();
printf("Congratulations : No error is found\n");
system("pause");
}
void program(void)
{
get_token();
if (!isprogram) {
printf("Error : Reserved Word 'program' is expected\n");
exit(-1);
}
get_token();
if (!isidentifier) {
c
exit(-1);
}
get_token();
if (!issemicolon) {
c
exit(-1);
}
get_token();
statement();
if (!isperiod) {
printf("Error : Symbol '.' is expected\n");
exit(-1);
}
}
void statement(void)
{
if(isbegin){
get_token();
statement();
while(issemicolon){
get_token();
statement();
}
if(isend){
get_token();
}
}else if(isnumbr){
get_token();
if(token.value == PLUS || token.value == MINUS || token.value == TIMES){
get_token();
if(!isnumbr){
printf("Error: 'Number' is expected\n", token.charvalue);
exit(-1);
}
}else{
printf("Error : 'Operator' is expected \n", token.charvalue);
exit(-1);
}
get_token();
}else{
printf("Eror : 'Begin' or 'Number' is expected\n");
exit(-1);
}
}
|
C
|
#ifndef EMAIL_H
#define EMAIL_H
#include <QString>
#include <QStringList>
struct Email {
QString author;
QString authorName;
QString subject;
Email(QString author, QString authorName, QString subject) :
author(author), authorName(authorName), subject(subject) {}
static Email parseArguments(QStringList args) {
QString subject = args.at(1);
QString author = args.at(3);
QString authorName = "";
int posOfAddressBeginning = author.indexOf('<');
if (posOfAddressBeginning != -1) {
authorName = author.left(posOfAddressBeginning - 1);
author = author.mid(posOfAddressBeginning + 1, author.lastIndexOf('>') - posOfAddressBeginning - 1);
}
return Email(author, authorName, subject);
}
};
#endif // EMAIL_H
|
C
|
/**********
Copyright 1990 Regents of the University of California. All rights reserved.
Author: 1985 Thomas L. Quarles
**********/
/*
*/
/*
(ckt,node)
* map the given node to the compact node numbering set of the
* specified circuit
*/
#include "spice.h"
#include <stdio.h>
#include "ifsim.h"
#include "sperror.h"
#include "cktdefs.h"
#include "suffix.h"
/*
Is a version of CKTmkVolt that first looks through the entire list of existing nodes to
find out if the node alreay exists before creating it.
This function is much less efficienct than CKTmkVolt due to the need to search through the
entire list of circuit nodes, and is no longer used.
*/
///<param name = "*ckt"> Circuit to operate on </param>
///<param name = "**node"> Node to be returned </param>
///<param name = "name"> Name of node </param>
int CKTmapNode(GENERIC *ckt, GENERIC **node, IFuid name)
{
register CKTnode *here;
int error;
IFuid uid;
CKTnode *mynode;
for (here = ((CKTcircuit *)ckt)->CKTnodes; here; here = here->next)
{
if (here->name == name)
{
if (node)
*node = (char *)here;
return(E_EXISTS);
}
}
/* not found, so must be a new one */
error = CKTmkNode((CKTcircuit*)ckt, &mynode); /*allocate the node*/
if (error)
return(error);
error = (*(SPfrontEnd->IFnewUid))((GENERIC *)ckt, &uid, (IFuid*)NULL, name, UID_SIGNAL, (GENERIC**)mynode); /* get a uid for it */
if (error)
return(error);
mynode->name = uid; /* set the info we have */
mynode->type = SP_VOLTAGE;
error = CKTlinkEq((CKTcircuit*)ckt, mynode); /* and link it in */
if (node)
*node = (GENERIC *)mynode; /* and finally, return it */
return(OK);
}
|
C
|
// Pass by value
void zero(int a, int b)
{
a = b = 0;
}
void main()
{
int n1 = 10, n2 = 20;
printf("%d %d\n",n1,n2);
zero(n1,n2);
printf("%d %d\n",n1,n2);
}
|
C
|
/* ----------------------------------------------------------------------------
* -- _____ ______ _____ -
* -- |_ _| | ____|/ ____| -
* -- | | _ __ | |__ | (___ Institute of Embedded Systems -
* -- | | | '_ \| __| \___ \ Zuercher Hochschule Winterthur -
* -- _| |_| | | | |____ ____) | (University of Applied Sciences) -
* -- |_____|_| |_|______|_____/ 8401 Winterthur, Switzerland -
* ----------------------------------------------------------------------------
*/
/**
* @file
* @brief Lab implementation
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct {
int students;
int points_6;
int best_mark;
int worst_mark;
double average_mark;
int mark_6;
int mark_5;
int mark_4;
int mark_3;
int mark_2;
int mark_1;
int passed;
} Statistics;
Statistics getStatistics(int points[], int len, int points_6);
int getMark(int points, int points_6);
void printStatistics(Statistics);
/**
* @brief Main entry point.
* @param[in] argc The size of the argv array.
* @param[in] argv The command line arguments
* with argv[0] being the command call
* argv[1] the 1st argument, ...
* argv[argc-1] the last argument.
* @returns Returns EXIT_SUCCESS (=0) on success,
* EXIT_FAILURE (=1) if more than one argument is given.
*/
int main(void)
{
int points[100];
int len = 0;
int all_points_inserted = 0;
int points_6 = 0;
Statistics statistics;
char rerun = 'y';
while (!all_points_inserted) {
(void)scanf("%d", &points[len]);
if (points[len] >= 0) {
len++;
} else if (points[len] == -1) {
all_points_inserted = 1;
// len++;
} else {
(void)printf("Points must be > 0!\n");
}
}
(void)printf("Insert points needed for a 6: \n");
(void)scanf("%d", &points_6);
do {
statistics = getStatistics(points, len, points_6);
(void)printStatistics(statistics);
(void)printf("Enter new minimal points for grade 6(y/n?)");
(void)scanf(" %s", &rerun);
if (rerun == 'y') {
(void)scanf("%d", &points_6);
}
} while (rerun == 'y');
return EXIT_SUCCESS;
}
Statistics getStatistics(int points[], int len, int points_6) {
Statistics statistics = { len, points_6 };
int grades[len];
for(int i = 0; i < len; i++) {
grades[i] = getMark(points[i], points_6);
}
int mark6 = 0;
int mark5 = 0;
int mark4 = 0;
int mark3 = 0;
int mark2 = 0;
int mark1 = 0;
int best_mark =1;
int worst_mark=6;
double average_mark;
for(int i=0; i<len; i++) {
best_mark = best_mark > grades[i] ? best_mark : grades[i];
worst_mark = worst_mark < grades[i] ? worst_mark : grades[i];
switch(grades[i]) {
case 1: mark1++;
break;
case 2: mark2++;
break;
case 3: mark3++;
break;
case 4: mark4++;
break;
case 5: mark5++;
break;
case 6: mark6++;
}
}
average_mark = (1*mark1+2*mark2+3*mark3+4*mark4+5*mark5+6*mark6)/(double)len;
statistics.best_mark = best_mark;
statistics.worst_mark = worst_mark;
statistics.average_mark = average_mark;
statistics.mark_1 = mark1;
statistics.mark_2 = mark2;
statistics.mark_3 = mark3;
statistics.mark_4 = mark4;
statistics.mark_5 = mark5;
statistics.mark_6 = mark6;
statistics.passed = mark6+mark5+mark4;
return statistics;
}
int getMark(int points, int points_6) {
double mark = 1 + ((5.0*points)/points_6);
if (mark > 6.0) {
mark = 6.0;
}
if ((mark - (int)mark) > 0.5) {
mark = ceil(mark);
} else {
mark = floor(mark);
}
return (int)mark;
}
void printStatistics(Statistics statistics) {
(void)printf("--------------------------------------------------------\n");
(void)printf("Statistics (%d students, %d points needed for mark 6):\n", statistics.students, statistics.points_6);
(void)printf("Mark 6: %d\n", statistics.mark_6);
(void)printf("Mark 5: %d\n", statistics.mark_5);
(void)printf("Mark 4: %d\n", statistics.mark_4);
(void)printf("Mark 3: %d\n", statistics.mark_3);
(void)printf("Mark 2: %d\n", statistics.mark_2);
(void)printf("Mark 1: %d\n\n", statistics.mark_1);
(void)printf("Best mark: %d\n", statistics.best_mark);
(void)printf("Worst mark: %d\n", statistics.worst_mark);
(void)printf("Average mark: %.2f\n", statistics.average_mark);
(void)printf("Mark >= 4: %d students %d Percent\n", statistics.passed, (statistics.passed*100)/statistics.students);
(void)printf("--------------------------------------------------------\n");
}
|
C
|
/**
* swap_int - swaps the value of two integers
*
* @a: address of int to be swaped with int on @b address
*
* @b: to be swapped @a.
*
*/
void swap_int(int *a, int *b)
{
int b1;
b1 = *b;
*b = *a;
*a = b1;
}
|
C
|
#include <stdio.h>
#include<stdlib.h>
int main(void) {
pid_t pid, sid;
int fichero;
pid = fork(); //iniciamos el fork
if (pid>0) // Este es el proceso padre
{
exit(0);
}
if(pid<0){
printf("Error en el proceso");
exit(0);
}
else // Proceso hijo
{
umask(0);
fichero = open("log_cpu", O_WRONLY|O_CREAT|O_TRUNC, 0600);
/* validar apertura de fichero */
if (fichero == -1) {
perror ("Error al abrir el archivo");
return -1;
}
/*Crear el nuevo sid*/
sid = setsid();
if (sid < 0) {
perror(" error en SID ");
}
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
while (1) {
char *buf=(char *)malloc(100);
FILE *fp = popen("top -bn2 | grep '%Cpu' | tail -1", "r");
fread(buf,100,1, fp);
write (fichero, buf, strlen(buf));
pclose(fp);
sleep(1);
}
return -1; //borrar cuando creamos daemon
}
}
|
C
|
#include <stdio.h>
#include<conio.h>
int main()
{
char temp,name[100];
int i,j,num,noc,nod,asc=97,days;
clrscr();
printf("Enter the value of n: ");
scanf("%d",&num);
noc=2*num;
nod=noc-1;
for(i=0;i<noc;i++)
{
name[i]=asc;
asc++;
}
days=nod;
j=(2*num)-1;
while(days!=0)
{
printf("\n The children pairs for day %d",days);
for(int i=0;i<2*num;i++)
{
printf("\n %c %c",name[i],name[j]);
j--;
}
for(int i=0;i<2*num;i++)
{
if(i==0)
{
temp=name[i];
}
name[i]=name[i+1];
if(i==(2*num)-1)
{
name[i]=temp;
}
}
days--;
}
getch();
return 0;
}
|
C
|
//
// new_game.c
// Projet_info
//
// Created by Rémi on 12/11/12.
// Copyright (c) 2012 Rémi. All rights reserved.
//
#include "bibli.h"
//=================================================================//
// Fonction de création de pseudo //
//=================================================================//
char *pseudo ()
{
char *name;
char pseudo[20];
//affichage du titre en ascii
aff_ng();
printf("Saisir votre pseudo, 20 caractères maximum : ");
scanf("%s", pseudo);
//allocation dynamique pour le pseudo
name = (char *)malloc(sizeof(pseudo));
strcpy(name, pseudo);
return name;
}
//=================================================================//
// Fonction qui gère la taille du labyrinthe //
//=================================================================//
/*
* Rien de bien compliqué içi, on affiche le menu de selection du niveau
* Puis on enregistre la difficulté, qui sera la taille du labyrinthe, dans la variable
* de la structure
*/
int difficult()
{
int ichoix;
int itaille;
aff_ng();
printf("Maintenant, choisis ton niveau:\n\n- 1 - Facile\n- 2 - Moyen");
printf("\n- 3 - Difficile\n- 4 - Impossible\n- 5 - Aléatoire \n\n");
printf("Saisir votre choix : ");
scanf("%i", &ichoix);
switch(ichoix)
{
case 1: itaille = 5; break;
case 2: itaille = 10; break;
case 3: itaille = 15; break;
case 4: itaille = 25; break;
case 5: itaille=rand()%20+5; break; //Chiffre choisit aléatoirement entre 5 et 25
default:
{
printf("Erreur: votre choix doit être compris entre 1 et 5\n");
printf("T'as voulu faire le malin, alors tu auras une surprise... \n");
itaille = 50; //petit piège, si l'utilisateur se trompe, taille 50 directement
}
}
printf("\nLabyrinthe de taille %i. \n", itaille);
sleep(2);
return(itaille);
}
//=================================================================//
// Fonction qui alloue dynamiquement la matrice //
//=================================================================//
//allocation dynamique de la matrice en fonction de la taille retournée par la fonction précédente
char** allocation_laby (int itaille)
{
char **gLaby;
int i;
gLaby = malloc(sizeof(*gLaby)*itaille);
for (i = 0; i < itaille; i++)
{
gLaby[i] = malloc(sizeof(**gLaby)*itaille);
}
return gLaby;
}
//=================================================================//
// Fonction de gestion de nouvelle partie //
//=================================================================//
//Fonction qui retourne la structure de jeu qui premettra de jouer la partie par la suite
sLabyrinthe nouveau_jeu()
{
char* cpseudo;
char* ccreation;
char **gLaby;
int itaille;
sLabyrinthe Resultat;
FctVideEcran();
//On lance la partie, en remplissant tout ce qui est demandé
cpseudo = pseudo();
viderBuffer();
FctVideEcran();
itaille = difficult();
FctVideEcran();
ccreation = datage();
gLaby = allocation_laby(itaille);
//Puis on insert tout dans la variable de type structure, pour pouvoir l'utiliser dans le moteur
Resultat.gLaby = gLaby;
Resultat.taille = itaille;
Resultat.pseudo = cpseudo;
Resultat.creation = ccreation;
Resultat.nv_partie = 1;
Resultat.temps = 0;
initialisation_carte(&Resultat);
creerLaby(&Resultat);
aff_ng();
viderBuffer();
printf("Prêt ? \n");
printf("Alors appuie sur une touche quand tu l'es vraiment...\n");
char tempo = get_one_char();
decompte(5);
printf("\n\n\n");
return Resultat;
}
|
C
|
#include "aref.h"
#include "string.h"
#pragma once
enum lexer_flags {
LexerRemoveSpace = 0x00000001,
LexerRemoveLine = 0x00000002,
LexerAddLine = 0x00000004,
LexerAddSpace = 0x00000008,
};
enum lexer_tokens {
LexerWhiteSpace, LexerIllegal, LexerLineFeed, LexerEof,
LexerKeyword, LexerPreprocessor,
LexerNumber, LexerString, LexerStringMultiline,
LexerComment, LexerCommentMultiline,
LexerIdentifier, LexerType, LexerNamespace,
LexerOperator, LexerBegin, LexerEnd, LexerBeginIndex, LexerEndIndex, LexerBeginExpression, LexerEndExpression,
// Analize
LexerEndOp, LexerPointer, LexerPoint, LexerFunction,
};
struct lexer
{
struct keyword
{
const char* name;
unsigned token;
int count; // cashed token
operator bool() { return name != 0; }
};
struct info
{
virtual void adderror(string name, int token) = 0;
virtual void addmember(string name, string type, int token) = 0;
void addkeywords(lexer* scheme);
void parse(const char* source, lexer* lex);
void parseimport(const char* source, lexer* lex);
};
const char* name;
const char** extensions;
static lexer* first;
lexer* next;
aref<keyword> keywords;
//
lexer(const char* name, const char** extensions, keyword* keywords);
//
const keyword* find(lexer_tokens t) const;
static bool issym(char e);
const keyword* match(const char* text) const;
static bool match(const char* text, const char* name);
const char* prev(const char* p0, const char* p, lexer_tokens& t) const;
static const char* word(const char* string, lexer_tokens& token, const lexer* scheme);
};
|
C
|
#include <stdio.h>
struct self_ref{
int a;
struct self_ref *b;
};
int main() {
typedef struct self_ref ref;
ref a,b,c;
a.a=5;
a.b=&b;
b.a=10;
b.b=&c;
c.a=15;
printf ("%d %d %d",*a.b,*b.b,c.a);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
float score;
printf("## Voce foi aprovado? ##\nInsira sua nota ");
scanf("%f", &score);
if (score >= 0 && score <= 10) {
if (score >= 7) {
printf("Parabens, voce foi aprovado!");
} else {
printf("Voce nao foi aprovado.");
}
} else {
printf("Por favor, insira uma nota de 0 a 10.");
}
return 0;
}
|
C
|
//
// Created by Jason on 26/03/2019.
//
#include <stdlib.h>
#include "circular_room.h"
struct RoomData {
float radius;
char level;
};
int circularFlightsOfStairs(RoomData *this){
if(this->level == 'G'){
return 0;
}
if(this->level == 'B'){
return -1;
}
return this->level - '0';
}
float circular_area(RoomData *this) {
float radius = this->radius;
return (2 * radius) * (2 * radius);
}
IRoom* new_circular_room(char level, float radius){
RoomData* this = malloc(sizeof(RoomData));
this->radius = radius;
this->level = level;
IRoom* room = malloc(sizeof(IRoom));
room->this = this;
room->area = &circular_area;
room->flightsOfStairs = &circularFlightsOfStairs;
return room;
}
|
C
|
#include<stdio.h>
#include<math.h>
int main()
{
int a[55];
int num=0;
scanf("%d",&num);
for (int i = 0; i < num; i++)
{
/* code */
scanf("%d",&a[i]);
}
for (int i = 0; i < num/2; i++)
{
/* code */
// int t=0;
// t = (i != num/2?(num)-((num/2)%i):(num/2)+1);
printf("%d %d\n",a[i],a[num-i]);//倒数公式为num-1-i
}
return 0;
}
|
C
|
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int main() {
int hours, mins, seconds;
char* offset = (char *)malloc(sizeof(char) * 2);
scanf("%d:%d:%d%s", &hours, &mins, &seconds, offset);
if(strncmp(offset, "PM", 2) == 0 && hours < 12){
hours += 12;
}
if(strncmp(offset, "AM", 2) == 0 && hours >= 12){
hours -= 12;
}
printf("%.2d:%.2d:%.2d\n", hours, mins, seconds);
return 0;
}
|
C
|
// Linked List Assignment #1 Spring 2018
/*
Done:
ptr makeNode( int )
void printList( ptr )
ptr insertFront( ptr, int )
int listLength( ptr )
More Linked List for you to add
- purpose & behavior explained in class
int isEmpty( ptr ) 1: if list is empty
int isInList( ptr, int ) 1: if val is in list
ptr getLoc( ptr, int ) ptr to location of val
int maxVal( ptr ) largest value
ptr maxLoc( ptr ) location of largest value
ptr insertBack( ptr, int ) add value to end of list
ptr insertAfter( ptr, ptr, int )
add value to list after loc
ptr removeFront( ptr ) delete first item
ptr removeBack( ptr ) delete last item
ptr removeThisOne( ptr, ptr ) delete item at this loc
*/
#include <stdio.h>
#include <stdlib.h>
struct boxtype
{
int val;
struct boxtype *link;
};
int maxVal( struct boxtype *front )
{
struct boxtype *mov;
int max;
mov = front;
max = mov->val;
while ( mov != NULL )
{
if ( mov->val > max )
max = mov->val;
mov = mov->link;
}
// printf("max %d", max);
return max;
}
int isInList( struct boxtype *front, int x )
{
struct boxtype *mov;
mov = front;
while ( mov != NULL )
{
if ( mov->val == x )
return 1;
mov = mov->link;
}
return 0;
}
int isEmpty( struct boxtype *front )
{
struct boxtype *mov;
mov = front;
if ( mov == NULL )
return 1;
return 0;
}
struct boxtype *getLoc( struct boxtype *box, int x )
{
}
struct boxtype *maxLoc( struct boxtype *front )
{
/* struct boxtype *mov, *rt;
int max;
mov = front;
max = maxVal(front);
while ( mov->link != NULL )
{
if ( mov->val == max )
rt = mov;
mov = mov->link;
}
return rt;
*/
}
struct boxtype *makeNode( int x )
{
struct boxtype *mynode;
mynode = malloc( sizeof( struct boxtype) );
mynode->val = x;
mynode->link = NULL;
return mynode;
}
int listLength( struct boxtype *front )
{
struct boxtype *mov;
int len = 0;
mov = front;
while ( mov != NULL )
{
len++;
mov = mov->link;
}
return len;
}
void printList( struct boxtype *front )
{
struct boxtype *mov;
printf("List: ");
mov = front;
while ( mov != NULL )
{
printf("%d ", mov->val);
mov = mov->link;
}
printf("\n");
}
struct boxtype *insertFront( struct boxtype *first, int num )
{
struct boxtype *tmp;
tmp = makeNode( num );
tmp->link = first;
first = tmp;
return first;
}
struct boxtype *insertAfter( struct boxtype *first, struct boxtype *here, int num )
{
struct boxtype *tmp, *mov;
mov = first;
while( mov->link != here->link )
mov = mov->link;
tmp = makeNode(num);
here = here->link;
tmp->link = here;
mov->link=tmp;
return first;
}
struct boxtype *insertBack( struct boxtype *first, int num )
{
struct boxtype *tmp, *mov;
tmp = makeNode( num );
mov = first;
while( mov->link != NULL )
{
mov = mov->link;
}
mov->link = tmp;
return first;
}
struct boxtype *removeFront( struct boxtype *first )
{
first = first->link;
return first;
}
struct boxtype *removeBack( struct boxtype *first )
{
struct boxtype *mov, *mov2;
mov = first;
mov2 = first;
while ( mov->link != NULL )
mov = mov->link;
while ( mov2->link != mov )
mov2 = mov2->link;
mov2->link = NULL;
return first;
}
struct boxtype *removeThisOne( struct boxtype *first, struct boxtype *here )
{
if ( first == here )
return first->link;
struct boxtype *tmp, *mov;
mov = first;
tmp = first;
while( tmp->link != here->link )
tmp = tmp->link;
while( mov->link != tmp )
mov = mov->link;
mov->link = tmp->link;
return first;
}
int main()
{
printf("here0");
struct boxtype *b, *start;
// struct boxtype *test;
int i, x;
printf("here1");
start = NULL;
/*
printList( start );
start = insertFront(start, 33);
printList(start);
start = insertBack(start, 7);
printList(start);
start = insertFront(start, 19);
printList(start);
test = start;
start = insertAfter(start, test, 7);
printList(start);
x = listLength( start );
printf("%d items\n", x);
printf("highest val: %d\n", maxVal(start));
test = test->link;
printList(start);
start = removeThisOne(start, test);
printList(start);
start = removeFront(start);
printList(start);
start = removeBack(start);
printList(start);
x = listLength( start );
printf("%d items\n", x);
printf("highest val: %d\n", maxVal(start));
// printf("highest loc: %d\n", maxLoc(start));
*/
printf("here2");
for ( i = 0; i < 10; ++i )
{
x = rand() % 100;
if ( x % 2 == 0 )
start = insertFront( start, x );
else
start = insertBack( start, x );
printf("here3");
printList( start );
}
printf("Len %d\n", listLength( start ) );
while ( !isEmpty( start ) )
{
x = start->val;
printf("%d\n", x);
start = removeFront( start );
printList( start );
}
while ( !isEmpty( start ) )
{
start = removeBack( start );
printList( start );
}
int mv;
struct boxtype *ml;
while ( !isEmpty( start ) )
{
mv = maxVal( start );
ml = maxLoc( start );
printf("big %d\n", mv );
start = removeThisOne( start, ml );
printList( start );
}
return 0;
}
|
C
|
//
// Created by Kingqi on 2019/2/13.
//
#include "../head/Sudoku.h"
void parseProblem(char *fileName, char *output);
char *getOutputName(char *fileName);
void write_1(char *);
void write_2(char *);
void write_3(char *);
void write_4(char *);
int readRes(char *);
int Sudoku(char *fileName)
{
char *outputName = getOutputName(fileName);
parseProblem(fileName,outputName);
//each cell has a value
write_1(outputName);
//each row has one value
write_2(outputName);
//each col has one value
write_3(outputName);
//each 3*3 box has one value
write_4(outputName);
//求解:
char *solution = SAT(outputName,1);
return readRes(solution);
}
int readRes(char *solution)
{
int n;
FILE *file = fopen(solution,"r");
fscanf(file,"s %d",&n);
return n;
}
void write_4(char *outputName)
{
FILE *output = fopen(outputName,"a");
int first , second;
for (int k = 1; k < 10; ++k) {
for (int a = 0; a < 3; ++a) {
for (int b = 0; b < 3; ++b) {
for (int u = 1; u < 4; ++u) {
for (int v = 1; v < 3; ++v) {
for (int w = v+1; w < 4; ++w) {
first = 81*((3*a+u)-1) + 9*((3*b+v)-1) + (k-1) +1;
second = 81*((3*a+u)-1) + 9*((3*b+w) -1) + (k-1) + 1;
fprintf(output,"-%d -%d 0\n",first,second);
}
}
}
}
}
}
for (int k = 1; k < 10; ++k) {
for (int a = 0; a < 3; ++a) {
for (int b = 0; b < 3; ++b) {
for (int u = 1; u < 3; ++u) {
for (int v = 1; v < 4; ++v) {
for (int w = u+1; w < 4; ++w) {
for (int t = 1; t < 4; ++t) {
first = 81*((3*a+u)-1) + 9*((3*b+v)-1) + (k-1) +1;
second = 81*((3*a+w)-1) + 9*((3*b+t) -1) + (k-1) + 1;
fprintf(output,"-%d -%d 0\n",first,second);
}
}
}
}
}
}
}
fclose(output);
}
void write_3(char *outputName)
{
FILE *output = fopen(outputName,"a");
int first,second;
for (int j = 1; j < 10; ++j) {
for (int k = 1; k < 10; ++k) {
for (int i = 1; i < 9; ++i) {
for (int l = i+1; l < 10; ++l) {
first = 81*(i-1) + 9*(j-1) + (k-1) + 1;
second = 81*(l-1) + 9*(j-1) + (k-1) +1;
fprintf(output,"-%d -%d 0\n",first,second);
}
}
}
}
fclose(output);
}
void write_2(char *outputName)
{
FILE *output = fopen(outputName,"a");
int first;
int second;
for (int i = 1; i < 10; ++i) {
for (int k = 1; k < 10; ++k) {
for (int j = 1; j < 9;j++){
for (int l = j+1; l < 10; ++l) {
first = 81*(i-1) + 9*(j-1) + (k-1) + 1;
second = 81*(i-1) + 9*(l-1) + (k-1) + 1;
fprintf(output,"-%d -%d 0\n",first,second);
}
}
}
}
fclose(output);
}
void write_1(char *outputName)
{
FILE *output = fopen(outputName,"a");
for (int i = 0; i < 81; ++i) {
for (int j = 1; j <= 9; ++j) {
fprintf(output,"%d ",i*9+j);
}
fprintf(output,"0\n");
}
fclose(output);
}
void parseProblem(char *fileName, char *outputName)
{
FILE *input = fopen(fileName,"r");
FILE *output = fopen(outputName,"w");
if(input==NULL)
{
printf("file not exist,please check it\n");
return;
}
int c = 0,t = 0 ;
char n;
int array[81]={0};
while (!feof(input))
{
fscanf(input,"%c",&n);
if (n=='\n' || n=='\r')
continue;
if (n != '0')
{
array[c] = n-48+t;
c++;
}
t+=9;
}
c--;//除去最后的一个文件尾
fprintf(output,"p cnf 729 %d\n",8829+c);
for (int i = 0; i < c; ++i) {
fprintf(output,"%d 0\n",array[i]);
}
fclose(input);
fclose(output);
}
char *getOutputName(char *fileName)
{
char *outputName = (char *)malloc(strlen(fileName)+1);
outputName = strcpy(outputName,fileName);
strcat(outputName,".cnf");
return outputName;
}
|
C
|
//
// File: ahnentafel.c
//
// @author Julie Sojkowski
//
// Purpose: user either enters command line arguments or uses the menu
// to select which option they would like, program then
// fulfulls the option
//
// // // // // // // // // // // // // // // // // // // // // // // //
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Function to calcualte the power of two integers
// base: the base integer
// exp: the exponent
// returns: the base number to the power of the exponent
int power( int base, int exp){
int ret = 1;
for (int i = 0; i< exp; i++){
ret = ret*base;
}
return ret;
}
// Function to print the menu and take in an integer for the option
// returns: the integer that the user imput as the option
int printMenu(){
printf("\n1) description\n");
printf("2) ahnentafel number (base 10)\n");
printf("3) ahnentafel number (base 2)\n");
printf("4) relation (e.g. mother's mother's father)\n");
printf("5) female X chromosome inheritance\n");
printf("6) exit\n");
int implen= 4;
char num[implen];
char *end;
if(fgets(num, implen, stdin)){
char *c;
if((c = strchr(num, '\n'))){ //check for newline
*c = 0; //assign newline to 0
} else {
scanf("%*[^\n]");
scanf("%*c");//clear upto newline
}
}
int imp = strtol(num, &end, 10);
return imp;
}
// Function to print the description for case 1
void prDescription(){
printf("The ahnentafel number is used to determine the relation\n");
printf("between an individual and each of his/her direct ancestors.\n");
}
// Function to make the string version of the realtion
// length: legth of the binary array
// bin: the binary number represented as an array of integers
// str: the string that will contain the relation
// returns: the number of generations
int getRelation(int length, int bin[], char str[]){
char mom[] = "mother";
char dad[] = "father";
char moms[] = "mother's ";
char dads[] = "father's ";
int gen = 0;
if (length < 1){
strcpy(str, "none");
return gen;
}
if( bin[1] == 1){
strcpy(str, moms);
gen++;
}
else if (bin[1] == 0){
gen++;
strcpy(str, dads);
}
for (int i = 2; i< length; i++){
if(i== length-1){ //check if it's the last digit
if( bin[i] == 1)
strcat(str, mom);
else if (bin[i] == 0)
strcat(str, dad);
}
else if( bin[i] == 1)
strcat(str, moms);
else if (bin[i] == 0)
strcat(str, dads);
++gen;
}
return gen;
}
// Function to convert base10 int to an integer array representing a binary number
// base10: the integer in base 10
// binary: the array that will get the binary number
// return: length of the binary array
int toBinary(int base10, int binary[]){
int len =0; //length of the binary array
int numlen = 32;
int revBin[numlen];
while(base10>0){
revBin[len] = base10 % 2;
base10 = base10/2;
len++;
}
int a =0;
for(int j = len-1; j>=0; --j){
binary[a]= revBin[j];
a++;
}
return len;
}
// Function to convert base10 int to a string array representing a binary number
// base10: the integer in base 10
// binary: the array that will get the binary number
// return: length of the binary array
int toBinaryStr(int base10, char binary[]){
int len =0; //length of the binary array
int numlen = 32;
int revBin[numlen];
while(base10>0){
revBin[len] = base10 % 2;
base10 = base10/2;
len++;
}
int a =0;
for(int j = len-1; j>=0; --j){
if(revBin[j] ==0)
binary[a]='0';
else binary[a]='1';
a++;
}
binary[a] = '\0';
return len;
}
// Function to convert string of "mother" / "father" into a binary string
// str: the string to be converted to binary
// binary: the string of 0's and 1's representing a binary number
// return: int, the number of generations
int strtoBin(char str[], char binary[]){
int gen =0;
char *pch[10];
pch[0] = strtok( str, " \n" );
char moms[] = "mother's";
char dads[] = "father's";
char mom[] = "mother";
char dad[] = "father";
char self[] = "self";
int i =0;
while ( pch[i] != NULL ) {
i++;
pch[i] = strtok( NULL, " \n" );
}
int count =1;
binary[0] = '1';
for(int j =0; j< i; j++){
char it[10];
strcpy( it, pch[j]);
if (strcmp(it, mom) == 0)
binary[count] = '1';
else if (strcmp(it, dad) == 0)
binary[count] = '0';
else if (strcmp(it, dads) == 0)
binary[count] = '0';
else if (strcmp(it, moms) == 0)
binary[count] = '1';
else if (strcmp(it, self) == 0)
binary[0]='1';
else{
binary[count] = '3'; //used for error checking
}
gen++;
count++;
}
binary[count] = '\0';
return gen;
}
// Function for the entirety of case 4:
// converts the string to binary and prints it
// converts the binary to base10 and prints it
// and prints the generations back
// gen: string of family relation
void case4(char gen[]){
int numlen = 32;
char strBin[numlen];
int generation = strtoBin(gen, strBin); // string f/m/f's/m's to string binary
int true =0;
for(unsigned int i =0;i< strlen(strBin); i++){
if( strBin[i] == '0'|| strBin[i] == '1')
true = 0;
else {
fprintf(stderr, "\nInvalid string! \n");
true = 1;
break;
}
}
if (true == 0){
printf("ahnentafel number in binary: %s", strBin);
int B10= (int) strtol(strBin, NULL, 2); //string binary to base 10
printf("\nbase-10 value: %i", B10);
printf("\ngenerations back: %i\n", generation);
}
}
// Function for the entirety of case 5:
// checks if the number of generations back is accepatble
// prints out the ahnentafel numbers for femal chromosome inheritence
void case5(void){
int numlen = 32;
char *end;
int arlen =3;
char base10[arlen];
printf("Number of generations back: ");
if(fgets(base10, arlen, stdin)){
char *p;
if((p=strchr(base10, '\n'))){//check exist newline
*p = 0;
} else {
scanf("%*[^\n]");scanf("%*c");//clear upto newline
}
}
int intB10 = strtol(base10, &end, 10);
while (intB10<0 || intB10 >9){
fprintf(stderr, "Invalid input, number of generations must be between 0 and 9!");
printf("\nNumber of generations back: ");
if(fgets(base10, arlen, stdin)){
char *p;
if((p=strchr(base10, '\n'))){//check exist newline
*p = 0;
} else {
scanf("%*[^\n]");scanf("%*c");//clear upto newline }
}
}
intB10 = strtol(base10, &end, 10);
}
printf("\n Printing %i generations back: \n", intB10);
int max = power(2, intB10+1);
char binary[numlen];
int length =0;
int check =0;
int ok;
for( int i =1; i < max; i++){ //goes through all the numbers possible in the generations
length = toBinaryStr(i, binary);
check =0;
for (int j =0; j< length; j++){ //goes though the binary array
if(binary[j] =='0' && binary[j+1]=='0'){ //checks if there are two 0's next to eachother
check++;
}
}
if (check==0) {
ok = (int) strtol(binary, NULL, 2);
printf(" %i, ", ok);
}
}
}
// Function for entirety of case 3:
// error checks to make sure the imput is binary
// converts binary to base 10 and prints out the base10 value
// get's the family relation and prints it
// prints the number of generations back
// bin: a charachter array of 0's and 1's representing a binary number
void case3(char bin[]){
int true =1;
int numlen = 32;
int charlen = 350;
for(unsigned int i =0; i< strlen(bin)-1; i++){
if( bin[i] == '0' || bin[i] == '1')
true = 0;
else{
printf("Invalid string!\n");
true = 1;
break;
}
}
int binary[numlen];
if (true == 0){
int B10= (int) strtol(bin, NULL, 2);
printf("base-10 value: %i", B10);
int len = toBinary(B10, binary);
char relation[charlen];
int gen =getRelation(len, binary,relation);
printf("\nfamily relation: %s", relation);
printf("\ngenerations back: %i\n", gen);
}
}
//Function for the entirety of case 2:
// converts base 10 to binary and prints it
// gets the family relation and prints it
// prints the number of generations
// base10: the base10 value entered to covert to binary
void case2(char base10[]){
char *end;
int numlen = 32;
int charlen = 350;
int binary[numlen];
int intB10 = strtol(base10, &end, 10);
int len = toBinary(intB10, binary);
printf("ahnentafel number in binary: ");
for (int f =0; f<len; f++){
printf("%i", binary[f]);
}
char strGen[charlen];
int gen = getRelation(len, binary, strGen);
printf("\nfamily relation: %s", strGen);
printf("\ngenerations back: %i\n", gen);
}
#define numlen 32
#define charlen 350
// Main function that checks how many command line arguments there are
// and prints out a menu or processes the commcand line argumaents
// argc: number of command line arguments
// argv: the command line arguments
// returns: exit_sucess
int main(int argc, char **argv){
if(argc == 1){
int imp = printMenu();
while(imp != 6){
if(imp == 1)
prDescription();
else if (imp == 2){
char base10[numlen];
printf("\nEnter the ahnentafel number in base-10: ");
fgets(base10, numlen, stdin);
case2(base10);
}
else if(imp == 3){
char bin[numlen];
printf("\nEnter the ahnentafel number in binary: ");
fgets(bin, numlen, stdin);
case3(bin);
}
else if(imp ==4){
printf("Enter family relation (e.g.) \"father's mother\": ");
char gen[charlen];
fgets(gen, charlen, stdin);
case4(gen);
}
else if(imp ==5){
case5();
}
else if(imp == 6){
printf("Goodbye.");
return EXIT_SUCCESS;
}
else fprintf(stderr, "\nUnknown operation!\n");
imp = printMenu();
}
}
else {
char enter[charlen];
strcpy(enter, argv[1]);
if (enter[strlen(enter)-1] =='b'){
case3(enter);
}
else if(enter[0] == 'm' || enter[0] =='f'){
for( int i =2; i< argc; i++){
enter[strlen(enter)] = ' ';
strcat(enter, argv[i]);
}
case4(enter);
}
else case2(enter);
}
return EXIT_SUCCESS;
}
|
C
|
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
#define DEBUG_MODE 0
int is_odd(int);
int main(){
int n;
scanf("%d",&n);
int *c = malloc(sizeof(int) * n);
for(int c_i = 0; c_i < n; c_i++){
scanf("%d",&c[c_i]);
}
/* if (DEBUG_MODE) */
/* printf("lower bound: %d\n", n / 2); */
int count = 0;
for (int i = 0; i < n - 1;) /* (n / 2) is the lower bound */
{
/* if (i == (n - 1)) /\* reached the end *\/ */
/* { */
/* if (DEBUG_MODE) */
/* printf("end\n"); */
/* break; */
/* } */
if ((i + 2 <= n - 1) && c[i + 2] == 0) /* jump two at a time */
{
i += 2;
count++;
if (DEBUG_MODE)
printf("jump by two\n");
}
else /* jump one at a time */
{
i++;
count++;
if (DEBUG_MODE)
printf("jump by one\n");
}
}
printf("%d", count);
return 0;
}
/* returns 0 if even, 1 if odd */
int is_odd(int n)
{
return n % 2;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//structure for the nodes of the trie
struct trie_node
{
char data;// stores the letters of the words
struct trie_node *child[27];// array of pointers
};
struct language
{
char eng[20];
char fr[20];
}word[10]={{"eat","manger"},{"head","tte"},{"hello","bonjour"},{"help","aidez"},{"sleep","dormir"},{"slope","pente"},{"there","l"},{"they","ils"},{"word","mot"},{"work","travail"}};
int binsearch(char key[])
{
int low, high, mid, result;
low = 0;
high = 10 - 1;
while (low <= high) {
mid = (low + high) / 2;
result = strcmp(word[mid].eng,key);
if (result > 0) {
high = mid - 1;
} else if (result < 0) {
low = mid + 1;
} else {
return mid;
}
}
}
//function for creating new nodes and assigning values to them
struct trie_node* newnode(char x)
{
int i;
struct trie_node *n;
n=(struct trie_node*)malloc(sizeof(struct trie_node));
n->data=x;
for (i=0;i<27;i++)
n->child[i]=NULL;//assigning the 26 pointers of the node to NULL
return n;//returning the pointer to structure
}
//function for inserting words into the trie for storage and manipulation
struct trie_node* insert(struct trie_node * root,char x[])
{
int index,l,length=strlen(x),i=0,k;
char a[10];
struct trie_node* temp=root;
for (l=0;l<length;l++)
{
index=(int)x[l]-(int)'a';/*Calculating the index of a letter eg. index of 'e' will be 70-65=5*/
if(temp->child[index]==NULL)
{
temp->child[index]=newnode(x[l]);/*passing the letter and creating a new node in the trie*/
temp=temp->child[index];
a[i++]=x[l];
}
else
{
a[i++]=x[l];
temp=temp->child[index];
}
}
a[i]='\0';/*after traversing the trie we make the node after the last letter as NULL,this marks the end of a word*/
k=binsearch(a);
temp->child[26]=newnode(k);
return root;
}
//function to search for the inserted words in the trie
int search(struct trie_node *root,char key[])
{
int lvl,length=strlen(key),index;
struct trie_node *temp=root;
for(lvl=0;lvl<length;lvl++)
{
index=(int)key[lvl]-(int)'a';
if(temp->child[index]!=NULL)
{
temp=temp->child[index];
}
else
return 0;
}
if(temp->child[26]==NULL)
return 0;
return 1;
}
//function to display the words in the trie
void display(struct trie_node *root)
{
int i;
if(root->child[26]==NULL)
{
for (i=0;i<26;i++)
{
if (root->child[i]!=NULL)
{
printf("%c",root->child[i]->data);
display(root->child[i]);/*recursively calling the display function so as to reach the end of the word*/
}
}
}
printf("\n");
}
//function which prints the rest of the substring for words which are present in the trie
void autocomplete (struct trie_node *root)
{
char key[10];
printf("Enter the substring:");
scanf("%s",key);
int index,l,c=0,i,j;
l=strlen(key);
struct trie_node *ptr=root;
while (ptr->data!=key[l-1] && c<l)/*run the while loop till we hit the last letter of the word*/
{
for (j=0;j<l;j++)
{
index=(int)key[j]-(int)'a';
if(ptr->child[index]!=NULL)
{
ptr=ptr->child[index];
c++;
}
}
}
printf("%s---->\n",key);//printing the initial substring
display(ptr);//displaying the rest of the word
}
void translate(struct trie_node *root,char key[])
{
int lvl,length=strlen(key),index,i=0;
struct trie_node *temp=root;
for(lvl=0;lvl<length;lvl++)//traversing through the word in the trie
{
index=(int)key[lvl]-(int)'a';
if(temp->child[index]!=NULL)
{
temp=temp->child[index];
}
else /*at every iteration we check for the next letter of the word and if it is not [resent we print that the word was not found*/
{
printf("\nWord not in the trie\n");
return;
}
}
if (temp->child[26]==NULL)/*if the node after the last letter is NULL then the word does not exist in the trie*/
{
printf("\nWord not in the trie\n");
return;
}
printf("%s\n",word[temp->child[26]->data].fr);/*if the above condition is false we print the translated french word*/
}
//driver program for the code
void main()
{
system("color 4a");
int choice,i,n,ch=1;
char str[10];
struct trie_node* root=NULL;
root=newnode('\0');
printf("\n\t\t\t\tTRIE and its application\n\n");
while(1)
{
printf("1--->INSERT\n");
printf("2--->SEARCH\n");
printf("3--->DISPLAY\n");
printf("4--->AUTOCOMPLETE\n");
printf("5--->TRANSLATE\n");
printf("6--->EXIT\n");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Insert words from 'eat','head','hello','help','sleep','slope','there','they','word','work'\n");
printf("How many words would you like to insert:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("Enter word:");
scanf("%s",str);
root=insert(root,str);
}
break;
case 2:
while(ch)
{
printf("Enter the word you would like to search:");
scanf("%s",str);
if(search(root,str)==1)
printf("Word Found");
else
printf("Word Not Found");
printf("\n");
printf("Press\n");
printf("1->CONTINUE\n");
printf("0->EXIT\n");
scanf("%d",&ch);
}
break;
case 3:
display(root);
break;
case 4:
autocomplete(root);
break;
case 5:
printf("Enter the word you would like to translate:");
scanf("%s",str);
translate(root,str);
break;
case 6:
exit(0);
}
}
}
|
C
|
#include "zxz_threadpool.h"
#if 0
void test(void *agr)
{
printf("hello\n");
}
#endif
void zxz_threadpool_manager_create()
{
pthread_t tid;
pthread_create(&tid, NULL, zxz_threadpool_agent, NULL);
pthread_detach(tid);
}
int zxz_threadpool_create(int size)
{
int i;
zxz_thread *thr;
struct epoll_event event;
epfd = epoll_create(1024);
zxz_threadpool_manager_create();
if(size <= 0)
size = 5;
pool.size = size;
pool.thr_list = zxz_list_create(NULL);
pool.thr_work = zxz_list_create(NULL);
pool.thr_wait = zxz_list_create(NULL);
for(i = 0; i < size; i++)
{
thr = NULL;
thr = zxz_thread_create(thr, i);
event.data.fd = thr->fd0;
event.events = EPOLLIN;
epoll_ctl(epfd, EPOLL_CTL_ADD, thr->fd0, &event);
pool.thr_list = zxz_list_add(pool.thr_list, thr);
}
return 0;
}
zxz_thread *zxz_threadpool_findbyfd0(int fd0)
{
zxz_thread *pthr = NULL;
zxz_list *plist = zxz_list_iterator(pool.thr_list);
for(; plist != zxz_list_end(pool.thr_list); plist = plist->next)
{
pthr = (zxz_thread *)plist->data;
if(pthr != NULL && pthr->fd0 == fd0)
return pthr;
}
return pthr;
}
void zxz_threadpool_waitingthread_run(void (*pfun)(void *), void *arg, ssize_t size)
{
zxz_list *pwait = zxz_list_begin(pool.thr_wait);
pwait = pwait->next;
zxz_thread *p = (zxz_thread *)pwait->data;
// printf("id=%d\n", p->id);
// printf("run\n");
if(pwait != NULL)
{
// printf("not NULL\n");
// count++;
zxz_thread_work(p, pfun, arg, size);
pool.thr_work = zxz_list_add(pool.thr_work, p);
pool.thr_wait = zxz_list_del(pool.thr_wait, p);
}
}
#if 0
void test(void *agr)
{
printf("hello\n");
}
#endif
void *zxz_threadpool_agent(void *arg)
{
int ret, i;
int fd;
zxz_thread *pthr;
while(1)
{
ret = epoll_wait(epfd, ep, 1024, -1);
/// printf("ret = %d\n", ret);
for(i = 0; i < ret; i++)
{
fd = ep[i].data.fd;
if(ep[i].events & EPOLLIN)
{
if((pthr = zxz_threadpool_findbyfd0(fd)) != NULL)
{
pool.thr_wait = zxz_list_add(pool.thr_wait, pthr);
if(zxz_list_contain(pool.thr_work, pthr))
{
printf("contain\n");
zxz_list_del(pool.thr_work, pthr);
}
else
{
printf("not contain\n");
}
// zxz_thread_work(pthr, test, NULL, 0);
epoll_ctl(epfd, EPOLL_CTL_DEL, pthr->fd0, NULL);
}
}
}
}
}
#if 0
int main()
{
zxz_threadpool_create(5);
zxz_threadpool_agent();
pthread_exit(NULL);
return 0;
}
#endif
#if 0
int main()
{
zxz_threadpool_create(5);
pthread_exit(NULL);
return 0;
}
#endif
|
C
|
#include <stdio.h>
#include <stdbool.h>
void test_function(bool (*function_pointer) (int x)) {
printf("addr passed function_pointer %p\n", function_pointer);
if (function_pointer(100)) {
printf(" run: true\n");
} else {
printf(" run: false\n");
}
}
bool function_outside_main(int x)
{
return x < 0;
}
int main(void)
{
// run with function defined globally
printf("addr function_outside_main %p\n", function_outside_main);
test_function(function_outside_main);
// run with function defined in this stack block
bool function_inside_main(int x) {
return x > 0;
}
printf("addr function_inside_main %p\n", function_inside_main);
test_function(function_inside_main); // shouldn't the address be valid?
}
|
C
|
#include <stdint.h>
#include "stm32f4xx_hal.h"
#include "arm_math.h"
#define input_sig_len 320
#define imp_sig_len 29
/*************function prototype***************/
float signal_mean(float *sig_src_arr,int sig_length);
float signal_variance(float *sig_src_arr,float _mean,int sig_length);
float signal_std(float _variance);
void plot_singnal(float *sig_src_arr,int sig_lenght);
void convolutions(float *sig_src_arr,int sig_length,
float *sig_imp_arr,int sig_imp_length,
float *dest_arr);
////////////////////////////////
extern void SystemClock_Config(void);
extern float inputSignal_f32_1kHz_15kHz[input_sig_len];
extern float32_t impulse_response [imp_sig_len] ;
float32_t output_sigal[imp_sig_len+input_sig_len];
float input_mean;
float input_variance;
float input_std;
float input_signal;
int main()
{
HAL_Init();
SystemClock_Config();
// //input_mean=signal_mean((float *)&inputSignal_f32_1kHz_15kHz[0], (int) input_sig_len);
//
// arm_mean_f32((float *)&inputSignal_f32_1kHz_15kHz[0], (int) input_sig_len,&input_mean);
// //input_variance=signal_variance((float *)&inputSignal_f32_1kHz_15kHz[0],(float) input_mean,(int) input_sig_len);
// arm_var_f32((float *)&inputSignal_f32_1kHz_15kHz[0],(int) input_sig_len,&input_variance);
//
// input_std= signal_std((float) input_variance);
// arm_std_f32((float *)&inputSignal_f32_1kHz_15kHz[0],(int) input_sig_len,&input_std);
while(1)
{
}
}
void convolutions(float *sig_src_arr,int sig_length,
float *sig_imp_arr,int sig_imp_length,
float *dest_arr)
{
uint16_t i,j,k;
for(i=0;i<sig_length+sig_imp_length;++i)
dest_arr[i]=0;
for(i=0;i<sig_length;i++)
{
for(j=0;j<sig_imp_length;j++)
{
dest_arr[i+j] = dest_arr[i+j]+sig_src_arr[i]*sig_imp_arr[j];
}
}
}
void plot_singnal(float *sig_src_arr,int sig_lenght)
{
for(int i=0;i<sig_lenght;++i)
{
sig_lenght =sig_src_arr[i];
for(int j=0;j<3000;j++);
}
}
float signal_mean(float *sig_src_arr,int sig_length)
{
float _mean=0.0f;
uint16_t i;
for(i=0;i<sig_length;i++)
{
_mean +=sig_src_arr[i];
}
return _mean;
}
float signal_variance(float *sig_src_arr,float _mean,int sig_length)
{
float _variance=0.0f;
uint16_t i;
for(i=0;i<sig_length;i++)
{
_variance += pow((sig_src_arr[i]-_mean),2);
}
return _variance/(sig_length-1);
}
float signal_std(float _variance)
{
float _std_variance= sqrt(_variance);
return _std_variance;
}
void SysTick_Handler(void)
{
HAL_IncTick();
HAL_SYSTICK_IRQHandler();
}
|
C
|
/*
stdio2.h
Extends basic input/output functionality.
Adrian Clinansmith
August 16, 2019
*/
#ifndef STDIO2_H
#define STDIO2_H
#include <stdio.h>
#include <stdlib.h>
/*
Reads chars from 'fp' and stores them in 'str' until 'num'-1 chars have been
read or either 'to' or EOF is reached, whichever happens first. The length of
'to' is determined by 'tosize' rather than a terminating NULL, therefore NULLs
can be read from 'fp'. If 'to' is found, it is included in 'str'. Regardless, a
NULL char is always appended to the end of 'str' after all other chars are
copied.
If 'num' is 0, there is no limit on the number of chars that can be read.
If 'to' is NULL and/or 'tosize' is 0, chars will be read until 'num'-1 or EOF.
On success, the number of chars read from 'fp' is returned. If 'fp' or 'str' is
NULL, no chars are read and -1 is returned.
*/
int fgetsto(char* str, size_t num, char* to, size_t tosize, FILE* fp);
/*
Reads chars from 'fp' and stores the address of the buffer containing the text
into '*strp' until 'to' or EOF is reached, whichever happens first. The length
of 'to' is determined by 'tosize' rather than a terminating NULL. If 'to' is
found, it is included in '*strp'. Regardless, a terminating NULL is always
appended to the end of '*strp' after all other chars are copied.
If '*strp' is NULL and/or '*num' is 0 then a buffer will be allocated and must
be freed by the user program. If '*strp' is NULL and '*num' is non-zero then the
buffer will be initially allocated with size '*num', and more will be allocated
if it is not enough.
Alternatively, before calling getto(), '*strp' can contain a pointer to an
allocated buffer '*num' bytes in size. If the initial buffer size is not enough,
more will be allocated.
In either case, on a successful call, '*strp' and '*num' are updated to reflect
the buffer address and allocated size respectively.
On success, the number of chars read is returned. If 'strp', 'num', or 'fp' is
NULL, -1 is returned before anything is read. If memory allocation fails, -1 is
returned and any previously allocated memory in '*strp' is freed.
*/
int getto(char** strp, size_t* num, char* to, size_t tosize, FILE* fp);
#endif
|
C
|
#include<stdio.h>
#define MAX 3
int cq[MAX];
int front = 0;
int back = 0;
int count = 0;
int val;
void enque()
{
printf("Enter the value\n");
scanf("%d",&val);
if(count == MAX)
printf("Overflow\n");
else
{
cq[back] = val;
back = (back + 1) % MAX;
count++;
}
}
void deque()
{
if(count == 0)
printf("Underflow\n");
else
{
front = (front + 1) % MAX;
count--;
}
}
int peek()
{
if(count == 0)
printf("Underflow\n");
else
{
printf("%d\n",cq[front]);
}
}
int display()
{
int j = count;
for(int i=front;j!=0;j--)
{
printf("%d ",cq[i]);
i = (i+1)%MAX;
}
}
int main()
{
int option;
do{
printf("Enter '1' to enque\n");
printf("Enter '2' to deque\n");
printf("Enter '3' to peek\n");
printf("Enter '4' to display\n");
printf("Enter '5' to exit\n");
scanf("%d",&option);
switch(option)
{
case 1:
enque();
break;
case 2:
deque();
break;
case 3:
peek();
break;
case 4:
peek();
break;
}
}while(option!=5);
}
|
C
|
#include <stdio.h>
int main()
{
int n,n1,n2,num,pos;
printf("ENTER THE SIZE OF ARRAY: ");
scanf("%d",&n);
int a[n+1];
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("ENTER THE NUMBERS BETWEEN WHICH GIVEN NUMBER SHOULD BE INSERTED: ");
scanf("%d %d ",&n1,&n2);
printf("\nENTER THE NUMBER TO BE INSERTED: ");
scanf("%d",&num);
for(int i=0;i<n;i++)
{
if(a[i]==n1)
{
pos = i;
}
else continue;
}
for(int i=n;i>=pos+2;i--)
{
a[i]=a[i-1];
}
a[pos+1] = num;
printf("THE ARRAY AFTER INSERTION IS: ");
for(int i=0;i<n+1;i++)
{
printf("%d ",a[i]);
}
return 0;
}
|
C
|
#include <stdio.h>
void smile();
int main(void){
smile(3);
printf("\n");
smile(2);
printf("\n");
smile(1);
printf("\n");
}
void smile(int times){
for(int i = 0; i<times; i++){
printf("Smile!");
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <time.h>
#include <unistd.h>
#include "potato.h"
int main(int argc, char *argv[])
{
int status;
int socket_fd;
struct addrinfo host_info;
struct addrinfo *host_info_list;
int port;
int num_players;
int num_hops;
const char *hostname = NULL;
//struct hostent *host_addr;
struct hostent *player_host;
struct sockaddr_in player_addr;//used to accept player connection
//check command line format
if(argc != 4){
printf("Usage: ./ringmaster <port_num> <num_players> <num_hops>\n");
return EXIT_FAILURE;
}
port = atoi(argv[1]);
num_players = atoi(argv[2]);
num_hops = atoi(argv[3]);
if(port <= 1024){
printf("Port number can not be smaller than 1024.\n");
return EXIT_FAILURE;
}
if(num_players <= 1){
printf("Number of players must be greater than 1.\n");
return EXIT_FAILURE;
}
if(num_hops < 0 || num_hops > 512){
printf("Number of hops must be between 0 and 512.\n");
return EXIT_FAILURE;
}
printf("Potato Ringmaster\n");
printf("Players = %d\n",num_players);
printf("Hops = %d\n",num_hops);
memset(&host_info, 0, sizeof(host_info));
host_info.ai_family = AF_UNSPEC;
host_info.ai_socktype = SOCK_STREAM;
host_info.ai_flags = AI_PASSIVE;
status = getaddrinfo(hostname, argv[1], &host_info, &host_info_list);
//printf("hostname: %s\n",hostname);
if (status != 0) {
printf("Error: cannot get address info for host (%s, %d)\n",hostname,port);
return EXIT_FAILURE;
}
socket_fd = socket(host_info_list->ai_family,
host_info_list->ai_socktype,
host_info_list->ai_protocol);
if (socket_fd == -1) {
printf("Error: cannot create socket (%s, %d)\n",hostname,port);
return EXIT_FAILURE;
}
int yes = 1;
status = setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
status = bind(socket_fd, host_info_list->ai_addr, host_info_list->ai_addrlen);
if (status == -1) {
printf("Error: cannot bind socket (%s, %d)\n",hostname,port);
return EXIT_FAILURE;
}
status = listen(socket_fd, 100);
if (status == -1) {
printf("Error: cannot listen on socket (%s, %d)\n",hostname,port);
return EXIT_FAILURE;
}
//printf("Waiting for connection on port %d\n", port);
//store all player's socket file descriptor
int player_socketfd[num_players];
//store all player's info
player player[num_players];
for(int i = 0; i < num_players; ++i){
socklen_t player_addr_len = sizeof(player_addr);
player_socketfd[i] = accept(socket_fd, (struct sockaddr *)&player_addr, &player_addr_len);
if(player_socketfd[i] < 0){
printf("Error: cannot accept connection on socket.\n");
return EXIT_FAILURE;
}
memset(&player[i],0,sizeof(player[i]));
player[i].player_id = i;
player[i].num_hops = num_hops;
player[i].num_players = num_players;
player[i].right_id = i + 1;
player[i].left_id = i - 1;
if(i == 0){
player[i].left_id = num_players - 1;
}
else if(i == num_players - 1){
player[i].right_id = 0;
}
//get player's host name and temporarily store
player_host = gethostbyaddr((char*)&player_addr.sin_addr, sizeof(struct in_addr), AF_INET);
strcpy(player[i].right_name, player_host->h_name);
//printf("right name:%s\n",player[i].right_name);
//receive player's port num and temporarily store
ssize_t s = recv(player_socketfd[i],&player[i].right_port,sizeof(player[i].right_port),0);
if (s == -1){
perror("recv() right port");
exit(EXIT_FAILURE);
}
//printf("right port: %d\n",player[i].right_port);
}
//rotate and store right neighbor's port and host name
int tmp_port = player[0].right_port;
char tmp_name[MAX_NAME];
strcpy(tmp_name, player[0].right_name);
for(int i = 0; i < num_players - 1; ++i){
int right = player[i].right_id;
player[i].right_port = player[right].right_port;
strcpy(player[i].right_name, player[right].right_name);
}
player[num_players - 1].right_port = tmp_port;
strcpy(player[num_players - 1].right_name, tmp_name);
//send player info struct to player
for(int i = 0; i < num_players; ++i){
status = send(player_socketfd[i], &player[i], sizeof(player[i]), 0);
if(status < 0){
perror("send player struct");
return EXIT_FAILURE;
}
}
//receive ready signal from players
//indicating already connected with neighbors
for(int i = 0; i < num_players; ++i){
int ready;
ssize_t s = recv(player_socketfd[i], &ready, sizeof(ready), 0);
if (s == -1){
perror("recv() ready");
exit(EXIT_FAILURE);
}
printf("Player %d is ready to play\n",i);
}
int shut_down = 0;
//if hop is 0, immediately shut down the game
if(num_hops == 0){
shut_down = 1;
}
for(int i = 0; i < num_players; ++i){
status = send(player_socketfd[i], &shut_down, sizeof(shut_down), 0);
if(status < 0){
perror("send shutdown");
return EXIT_FAILURE;
}
}
if(num_hops == 0){
freeaddrinfo(host_info_list);
close(socket_fd);
for(int i = 0; i < num_players; ++i){
close(player_socketfd[i]);
}
return EXIT_SUCCESS;
}
//start passing potato
//sleep(1);
//initialize potato
potato potato;
memset(&potato, 0, sizeof(potato));
potato.num_hops = num_hops;
potato.remain_hops = num_hops;
srand((unsigned)time(NULL));
int first_player = (rand()) % num_players;
printf("Ready to start the game, sending potato to player %d\n",first_player);
//send potato to first player
status = send(player_socketfd[first_player], &potato, sizeof(potato), 0);
if(status < 0){
perror("send potato to first player");
return EXIT_FAILURE;
}
//set up fd_set to monitor fd activity
fd_set players_fd;
int max_sd = player_socketfd[0];
while(1){
FD_ZERO(&players_fd);
for (int i = 0; i < num_players; ++i) {
FD_SET(player_socketfd[i], &players_fd);
if (player_socketfd[i] > max_sd) {
max_sd = player_socketfd[i];
}
}
if(select(max_sd + 1, &players_fd, NULL, NULL, NULL) < 0){
perror("select players");
return EXIT_FAILURE;
}
for(int i = 0; i < num_players; ++i){
//activity at any player socket indicate the end of game
if(FD_ISSET(player_socketfd[i], &players_fd)){
//receive potato
memset(&potato, 0, sizeof(potato));
ssize_t s = recv(player_socketfd[i], &potato, sizeof(potato), 0);
if (s == -1){
perror("recv() last potato");
exit(EXIT_FAILURE);
}
//send shutdown signal to all players
for(int i = 0; i < num_players; ++i){
int shutdownstat = shutdown(player_socketfd[i],SHUT_RDWR);
if(shutdownstat < 0){
printf("shutdown at player %d\n",i);
return EXIT_FAILURE;
}
}
//print trace of player id
printf("Trace of potato:\n");
for(int i = 0; i < num_hops; ++i){
if(i == num_hops - 1){
printf("%d\n",potato.trace[i]);
}
else{
printf("%d,",potato.trace[i]);
}
}
freeaddrinfo(host_info_list);
close(socket_fd);
for(int i = 0; i < num_players; ++i){
close(player_socketfd[i]);
}
return EXIT_SUCCESS;
}//if FD_ISSET
}//for loop
}//while loop
return EXIT_SUCCESS;
}
|
C
|
/* login : g.isaac@groupecerco.com */
#include <stdio.h>
#include <stdlib.h>
int ft_is_prime(int nb);
int ft_is_prime(int nb)
{
int i;
i = nb - 1;
if (nb > 1)
while (nb % i--)
;
return ((!i && nb != 1) ? 1 : 0);
}
int main(void)
{
int i;
i = 0;
while (i++ <= 100)
printf("ft_is_prime(%i) => %i\n", (i - 1), ft_is_prime(i - 1));
return (0);
}
|
C
|
#include "proco.h"
int main (int argc, char *argv[])
{
if(argc != 6){
printf("\nERROR: the program should take 5 arguments!\n\n");
exit(-1);
}
int producers = atoi(argv[1]);
int consumers = atoi(argv[2]);
int numOfRands = atoi(argv[3]);
int circSize = atoi(argv[4]);
seed = atoi(argv[5]);
fp = fopen("./producers_in.txt", "w");
fc = fopen("./consumers_out.txt", "w");
working_prods = producers;
w = producers;
total_nums = producers*numOfRands;
n = producers*numOfRands;
cb = (circular_buffer*)malloc(sizeof (struct circular_buffer));
cb_init(cb, circSize, 1);
init();
PRODUCERS prods[producers]; // Initialize array of PRODUCERS
int rc;
int i;
int pID[producers]; // Producers ID
pthread_t *p;
p = malloc(producers * sizeof(pthread_t));
if (p == NULL) {
printf("NOT ENOUGH MEMORY!\n");
exit(-1);
}
// Create producer threads
for(i = 0; i < producers; i++){
prods[i].randoms = numOfRands; // Number of randoms
pID[i] = i + 1;
prods[i].threadID = pID[i]; // ID
rc = pthread_create (&p[i], NULL, execProds, &prods[i]);
if(rc != 0){
printf("ERROR: return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
int cID[consumers]; // Consumers ID
pthread_t *c;
c = malloc(consumers * sizeof(pthread_t));
if (c == NULL) {
printf("NOT ENOUGH MEMORY!\n");
exit(-1);
}
// Create consumer threads
for(i = 0; i < consumers; i++){
cID[i] = i + 1;
rc = pthread_create (&c[i], NULL, execCons, &cID[i]);
if(rc != 0){
printf("ERROR: return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
// Join producer threads
for(i = 0; i < producers; i++){
rc = pthread_join (p[i], NULL);
if(rc != 0){
printf("ERROR: return code from pthread_join() is %d\n", rc);
exit(-1);
}
}
// Join consumer threads
for(i = 0; i < consumers; i++){
rc = pthread_join (c[i], NULL);
if(rc != 0){
printf("ERROR: return code from pthread_join() is %d\n", rc);
exit(-1);
}
}
fclose(fp); // Close fp file
fclose(fc); // Close fc file
free(p);
free(c);
free(cb);
destroy();
printf("\n\n");
return 1;
}
|
C
|
/* Function Pointers and Strings */
// The integer constant literal 0 has different meanings depending upon the
// context in which it's used. In all cases, it is still an integer constant
// with the value 0, it is just described in different ways.
//
// If a pointer is being compared to the constant literal 0, then this is a
// check to see if the pointer is a null pointer.
//
// This 0 is then referred to as a null pointer constant. The C standard
// defines that 0 cast to the type void * is both a null pointer and a null
// pointer constant.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char *string_to_lower(const char *str)
{
char *tmp = (char *) malloc (strlen(str) );
char *start = tmp;
while ( *str != 0 ){
*tmp++ = tolower(*str++);
}
*tmp = 0;
return start;
}
int compare( char *s1, char *s2)
{
return strcmp(s1, s2);
}
int compare_ign_case( char *s1, char *s2)
{
char *tmp_s1 = string_to_lower(s1);
char *tmp_s2 = string_to_lower(s2);
int result = strcmp(tmp_s1, tmp_s2);
free(tmp_s1);
free(tmp_s2);
return result;
}
typedef int (*fun_ptr_operation) ( char *, char *);
void sort (char *array[], int size, fun_ptr_operation operation)
{
int i;
char *tmp;
int swap = 1;
while(swap){
swap = 0;
for(i = 0; i < size-1; i++){
if (operation( array[i], array[i+1] ) > 0 ){
swap = 1;
tmp = array[i];
array[i] = array[i+1];
array[i+1] = tmp;
}
}
}
}
void display_names(char *name[], int size)
{
int i ;
for(i = 0; i < size; i++){
printf("%s\t", name[i]);
}
printf("\n");
}
int main()
{
char *name_1[6] = {"Ted", "Bob", "Alice", "Kkbox", "apple", "bob"};
char *name_2[6] = {"Ted", "Bob", "Alice", "Kkbox", "apple", "bob"};
// care about case
sort(name_1, 6, compare);
display_names(name_1, 6);
// ignore about case
sort(name_2, 6, compare_ign_case);
display_names(name_2, 6);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
void *f1(void *p)
{
int *n=(int*)p;
printf("%d\n",*n);
/*int count=0,i;
for(i=0;i<5;i++)
{
count=count+a[i];
}
printf("%d",count);
printf("DEF\n");*/
//return NULL;
}
int main()
{
pthread_t t1;
int a=5;
pthread_create(&t1,NULL,f1,(void*)&a);
printf("ABC\n");
sleep(5);
return 0;
}
|
C
|
#include <stdio.h>
#include "Square.h"
static void square_draw()
{
printf("Inside Square::draw() method.\n");
}
Shape_t new_Square()
{
Shape_t quadrado =
{
.draw = square_draw
};
return quadrado;
}
|
C
|
//This file is the constants in the project.
//
//Created by Xiaoxue Xin on 11/3/18.
//
#ifndef _CONSTANTS_H_
#define _CONSTANTS_H_
//constant maximum color value
const int MAX_COLOR = 255;
//constant minimum color value
const int MIN_COLOR = 0;
//initial row and column value
const int INITIAL_COL_ROW = -99999;
//lower bound of choice
const int LOW_BOUND_CHOICE = 0;
//first choice
const int FIRST_CHOICE = 1;
//second choice
const int SECOND_CHOICE = 2;
//third choice
const int THIRD_CHOICE = 3;
//forth choice
const int FORTH_CHOICE = 4;
//exit the program
const int EXIT_CHOICE = 5;
//set red for object
const int RED_INDEX = 1;
//set green for object
const int GREEN_INDEX = 2;
//set blue for object
const int BLUE_INDEX = 3;
//set black for object
const int BLACK_INDEX = 4;
//set white for object
const int WHITE_INDEX = 5;
//lower bound of object
const int LOWER_BOUND = 0;
//unvalid difference
const int UNVALID_DIFF = 2;
//rectangle coordinate choice
const int RECT_INDEX_FIRST = 1;
//rectangle coordinate choice
const int RECT_INDEX_SECOND = 2;
//rectangle coordinate choice
const int RECT_INDEX_THIRD = 3;
//unvalid center
const int CENTER_BOUND_ROW = 1;
//unvalid center
const int CENTER_BOUND_COL = 1;
//fill the rectangle
const int FILL_RECT = 2;
//not fill the rectangle
const int NOT_FILL_RECT = 1;
//ignore the length of string
const int RANGE_STRING = 200;
#endif
|
C
|
#ifndef LL_DOUBLY_H
#define LL_DOUBLY_H
/** Node in the linked list. */
struct ll_node {
struct ll_node *next;
void *object;
};
typedef struct ll_node ll_node_t;
struct linked_list {
struct ll_node *head;
unsigned int length;
};
typedef struct linked_list linked_list_t;
/**
* ll_create - create linked list
*
* return:
* - NULL if fail
* - linked_list_t pointer
*/
linked_list_t *ll_create(void);
/**
* Destroys a linked list. This will free up its memory and the memory taken
* by its nodes. This also DOES free up the memory taken up by the objects
* contained within the nodes.
*
* list: The list to destroy.
*/
void ll_destroy(linked_list_t *list);
int ll_add_head(linked_list_t *list, void *object, int size);
int ll_add_tail(linked_list_t *list, void *object, int size);
int ll_del_head(linked_list_t *list);
#endif /* LL_DOUBLY_H */
|
C
|
/*
1) Backtracking 시 st +1 -> i+1... 실수.. 어쩐지 중복되더라
2) 중복되는 경우를 안빼줌. break로써 제외.(preprocessing)
3) C 컴파일러 -> 변수 선언은 반드시 코드의 맨 처음
*/
#include <stdio.h>
#include <string.h>
#define MAXN 110
#define MAXLEN 20
int n;
char iWord[MAXN][MAXLEN];
int m, lenOfAcronym;
char aWord[MAXN][MAXLEN];
int lenOfaWord[MAXN];
int result;
void pproc(char *acronym, char *fullname) {
char *ptr, lacro[MAXLEN];
int len, i, j, k, isIgnored;
strcpy(lacro, acronym);
strlwr(lacro);
m = 0;
ptr = strtok(fullname, " ");
do {
if (ptr) {
//printf("PP : %s\n", ptr);
isIgnored = 0;
for (i = 0; i < n; i++)
if ( strcmp(ptr, iWord[i]) == 0 ) {
isIgnored = 1;
break;
}
if (!isIgnored) {
len = strlen(ptr);
k = 0;
for (i = 0; i < len; i++) {
for(j = 0; j < lenOfAcronym; j++)
if ( ptr[i] == (acronym[j] - 'A'+'a') ) {
aWord[m][k] = ptr[i] - 'a' + 'A';
k++;
break;
}
}
lenOfaWord[m] = k;
m++;
}
}
ptr = strtok(NULL, " ");
} while (ptr != NULL);
}
void find(char *acro, int index1, int index2, int st, int depth) {
//int k;
//for (k =0; k < depth; k++) printf("..");
//printf("(%d %d %d / %d, %d)\n", index1, index2, st, lenOfAcronym - index1, m - index2);
if ( lenOfAcronym - index1 >= m - index2) {
if ( lenOfAcronym == index1 ) {
result++;
// printf("...(%d %d %d) : %d\n", index1, index2, st, result);
return 0;
}
int i;
for (i = st; i < lenOfaWord[index2]; i++) {
if ( acro[index1] == aWord[index2][i] ) {
find (acro, index1 + 1, index2 , i + 1,depth+1);
find (acro, index1 + 1, index2 + 1, 0,depth+1);
}
}
}
}
int main() {
int i, j;
while (scanf("%d", &n) != EOF) {
if ( n == 0 ) break;
char acronym[MAXLEN], fullname[MAXLEN*10];
for (i = 0 ; i < n; i++)
scanf("%s",iWord[i]);
do {
result = 0;
scanf("%s", acronym); lenOfAcronym = strlen(acronym);
gets(fullname);
if ( strcmp(acronym, "LAST") == 0 && strcmp(fullname,"CASE") == 0) break;
pproc(acronym, fullname);
/*for (i = 0; i < m; i++ ) {
for (j = 0; j < lenOfaWord[i]; j++)
printf("%c",aWord[i][j]);
printf("\n");
}*/
find(acronym, 0, 0, 0, 0);
if (result > 0)
printf("%s can be formed in %d ways", acronym, result);
else
printf("%s is not a valid abbreviation", acronym);
} while (1);
}
return 0;
}
|
C
|
/*
* Standard library includes
*/
#include <stdint.h>
/*
* Utility Library Includes
*/
#include "util_geo.h"
#include "util_angle.h"
#include "util_macros.h"
/*
* Private Function Prototypes
*/
static uint16_t sanitiseAngleTdeg(int16_t a);
/*
* Public Functions
*/
uint16_t reciprocal_deg(int16_t a)
{
a *= 10;
uint16_t result = reciprocal_tdeg(a);
return div_round_pos(result, 10);
}
uint16_t reciprocal_tdeg(int16_t a)
{
uint16_t angle = sanitiseAngleTdeg(a);
return (angle < 1800) ? (angle + 1800) : (angle - 1800);
}
uint16_t mirror_deg(int16_t a, int16_t mirror)
{
uint16_t result = mirror_tdeg(a * 10, mirror * 10);
return div_round_pos(result, 10);
}
uint16_t mirror_tdeg(int16_t a, int16_t mirror)
{
uint16_t sanitised_a = sanitiseAngleTdeg(a);
uint16_t sanitised_mirror = sanitiseAngleTdeg(mirror);
return sanitiseAngleTdeg(3600 + sanitised_mirror - sanitised_a);
}
float radians(float deg) { return deg * 2 * PI / 360.0f; }
float degrees(float rad) { return rad * 360.0f / 2 * PI; }
/*
* Private Functions
*/
static uint16_t sanitiseAngleTdeg(int16_t a)
{
while (a >= 3600) { a -= 3600; } // Bring below +360degrees
while (a <0) { a += 3600; } // Bring above 0degrees
return (uint16_t)a;
}
|
C
|
// c program to rotate an array b d elements
// array rotation - method juggling algorithm
#include <stdio.h>
// function to print array
void printArray(int arr[], int size);
// function to get greatest common of a and b
int gcd(int a, int b);
// function to left rotate arr[] of size n by d
void leftRotate(int arr[], int d, int n) {
int i, j, k, temp;
int g_c_d = gcd(d, n);
for (i=0; i<g_c_d; i++) {
// move i-th values of blocks
temp = arr[i];
j=i;
while (1) {
k=j+d;
if(k>=n)
k=k-n;
if(k==i)
break;
arr[j] = arr[k];
j=k;
}
arr[j] = temp;
}
}
// utility function to print array
void printArray(int arr[], int n) {
int i;
for (i=0; i<n; i++)
printf("%d ",arr[i]);
}
// utility function to get greatest common of a and b
int gcd(int a, int b) {
if (b==0)
return a; // I got it here my mistake I just end the program.. :D insert return 0;
else
return gcd(b,a%b);
}
// main program to run/test above functions
int main() {
int arr[] = {1,2,3,4,5,6,7};
leftRotate(arr,2,7);
printArray(arr,7);
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int i,size,position,insitem;
printf("Enter size\n");
scanf("%d",&size);
int a[size],temp[size+1];
printf("Enter numbers in array\n");
for(i=0; i<size; i++)
scanf("%d",&a[i]);
printf("Enter element to be inserted\n");
scanf("%d",&insitem);
printf("Enter position for an element to be inserted (0 to %d)\n", size);
scanf("%d",&position);
for(i=0; i<=size; i++)
{
if(i<position)
temp[i]=a[i];
if(i>position)
temp[i]=a[i-1];
if(i==position)
temp[i]=insitem;
}
printf("Array after inserting %d\n",insitem);
for(i=0; i<=size; i++)
printf("%d\n",temp[i]);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int fun(int a,int b)
{
int i,n,k;
k=0;
for(i=a;i<=b;i++)
{
if((i%400==0)||(i%4==0&&i%100!=0) )
{
printf("%d\n",i);
k++;
}
}
return k;
}
int main ()
{
int ans,a,b;
printf("J褸ab");
scanf("%d %d",&a,&b);
ans=fun(a,b);
printf("@%dӶ|~",ans);
}
|
C
|
#include <stdio.h>
#include <math.h>
double suma(double n)
{
double suma = 0;
for(int i = 0; i<=n; i++)
{
suma += 2*pow(-1, i) * pow(3, 0.5 - i) / (2 * i + 1);
}
return suma;
}
int main(void)
{
for(int n = 0; n<=50; n++)
{
printf("%d %.15f\n", n, suma(n));
}
}
|
C
|
/* cat.c -- cat utility: display file contents */
/* $Id$ */
/* Carlos Duarte, 981004 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUMBER_ALL 1
#define NUMBER_NON_BLANKS 2
/* flags */
static int visualize = 0;
static int mark_end = 0;
static int show_tabs = 0;
static int number_lines = 0;
static int squeeze_blanks = 0;
static void
warn(char *s) {
fprintf(stderr, "%s -- could not read\n", s);
}
static void
die(char *s) {
fprintf(stderr, "%s -- can not write\n", s);
exit(1);
}
#define PUTCHAR(c) switch (putchar(c)) case EOF: die("putchar")
static int
cat(char *filename)
{
FILE *f;
int c;
static int line_counter = 0; /* count lines */
static int oc = '\n'; /* old character */
static int ooc = -1; /* old old character */
if (filename == NULL || strcmp(filename, "-") == 0)
f = stdin;
else if ((f = fopen(filename, "r")) == NULL) {
perror(filename);
return -1;
}
while ((c = getc(f)) != EOF) {
if (squeeze_blanks && ooc == '\n' && oc == '\n' && c == '\n')
continue;
if (oc == '\n') {
if (number_lines == NUMBER_ALL) {
if (printf("%6d\t", ++line_counter) == EOF)
die("printf");
} else if (number_lines == NUMBER_NON_BLANKS
&& c != '\n') {
if (printf("%6d\t", ++line_counter) == EOF)
die("printf");
}
}
if (c == '\n') {
if (mark_end)
PUTCHAR('$');
PUTCHAR('\n');
} else {
if (c == '\t') {
if (show_tabs) {
PUTCHAR('^');
PUTCHAR('I');
} else
PUTCHAR('\t');
} else if (visualize) {
if (c > 127) {
PUTCHAR('M');
PUTCHAR('-');
c -= 128;
}
if (c < ' ') {
PUTCHAR('^');
PUTCHAR(c+'@');
} else if (c == 127) {
PUTCHAR('^');
PUTCHAR('?');
} else
PUTCHAR(c);
} else
PUTCHAR(c);
}
ooc = oc;
oc = c;
}
if (ferror(f))
warn(filename);
if (f != stdin)
fclose(f);
return 0;
}
static int
copy(char *fn)
{
int c;
FILE *f;
if (fn == NULL || strcmp(fn, "-") == 0)
f = stdin;
else if ((f = fopen(fn, "r")) == NULL) {
perror(fn);
return -1;
}
while ((c = getc(f)) != EOF)
PUTCHAR(c);
if (ferror(f))
warn(fn);
if (f != stdin)
fclose(f);
return 0;
}
int
main(int argc, char *argv[])
{
int i;
int (*fn_cater)(char *);
for (i=1; i<argc && argv[i][0] == '-'; i++) {
char *s = &argv[i][1];
while (*s) switch (*s++) {
case 'A':
visualize = mark_end = show_tabs = 1;
break;
case 'b':
number_lines = NUMBER_NON_BLANKS;
break;
case 'e':
visualize = mark_end = 1;
break;
case 'E':
mark_end=1;
break;
case 'n':
number_lines= NUMBER_ALL;
break;
case 's':
squeeze_blanks=1;
break;
case 't':
show_tabs=visualize=1;
break;
case 'T':
show_tabs=1;
break;
case 'u':
setbuf(stdout, NULL);
break;
case 'v':
visualize=1;
break;
default:
fprintf(stderr,
"usage: cat [-AbeEnstTuv] [files ...]\n");
exit(1);
}
}
fn_cater = cat;
if (visualize+mark_end+show_tabs+number_lines+squeeze_blanks == 0)
fn_cater = copy;
if (i<argc)
for (; i<argc; i++)
fn_cater(argv[i]);
else
fn_cater(NULL);
return 0;
}
|
C
|
#include "bst.h"
#include <stdio.h>
int main(int argc, char *argv[]) {
int *a = {1,2,3,4};
int b = *a;
printf("%d\n", b);
//tree *t;
//t->root = 2;
//insert(*t, 2);
//insert(*t, 1);
//insert(*t, 3);
}
|
C
|
#include "readwriter.h"
pthread_mutex_t mutex;
sem_t semaphore[2];
char buffer[N_BUFFER][13], temp[13];
int ptr_read = 0, finish = 0;
int escolher_ficheiro(){ /*Escolhe ficheiro entre 5, aleatoriamente*/
int id_file = rand() % 5;
return id_file;
}
int leitor(){
int file, i, wrong, x;
char linha[10], primeira[10], filename[13];
while(1){
wrong = 0;
i = 0;
if(finish) break;
if(sem_wait(&semaphore[0]) != 0){
perror("Wait on semaphore0: Failed");
return -1;
}
if(finish) break;
if(pthread_mutex_lock(&mutex) != 0){
perror("Lock mutex: Failed");
return -1;
}
strcpy(filename, buffer[ptr_read]);
if(strcmp(filename, "") == 0){
pthread_mutex_unlock(&mutex);
continue;
}
ptr_read = (ptr_read + 1) % N_BUFFER;
if(pthread_mutex_unlock(&mutex) != 0){
perror("Unlock mutex: Failed");
return -1;
}
if(sem_post(&semaphore[1]) != 0){
perror("Post semaphore1: Failed");
return -1;
}
file = open(filename, O_RDONLY | PERMISSION_CODE_R);
if (file < 0){
perror("Open: Failed.\n");
continue;
}
if(flock(file, LOCK_SH) < 0){
perror("Flock on Lock: Failed.\n");
close(file);
return -1;
}
x = read(file, primeira, 10);
printf("%d\n", x);
if(x < 10){ /*Le a primeira linha para comparacao*/
perror("First Read: Failed.\n");
flock(file, LOCK_UN);
close(file);
continue;
}
while(read(file, linha, 10) != 0){ /*Enquanto houver linhas no ficheiro*/
if(strncmp(primeira, linha, 10) != 0){
perror("Linha nao corresponde: Erro.\n"); /*Se linha diferente da primeira da erro*/
wrong = 1;
}
if(wrong) break;
i++;
}
if(flock(file, LOCK_UN) < 0){
perror("Flock on Unlock: Failed.\n");
close(file);
return -1;
}
close(file);
if(wrong) continue;
if(i != (N_LINES - 1)){ /*Se acabou o ficheiro, sucesso*/
perror("Não acabou o ficheiro: Erro.\n");
return -1;
}
printf("Read success on %s!\n", filename);
}
return 0;
}
int main(){
int i, receive;
pthread_t thread_array[N_THREAD_READ];
int ptr_write = 0;
srand(time(NULL));
if(pthread_mutex_init(&mutex, NULL) != 0){
perror("Initialize mutex: Failed");
return -1;
}
for(i = 0; i < 2; i++){
if(sem_init(&semaphore[i], 0, i * N_BUFFER) != 0){
perror("Initialize semaphore: Failed");
return -1;
}
}
for(i = 0; i < N_THREAD_READ; i++){
if(pthread_create(&thread_array[i], NULL, (void *) leitor, NULL) != 0){
perror("Create thread: Failed");
return -1;
}
}
while(1){
if(sem_wait(&semaphore[1]) != 0){
perror("Wait semaphore1: Failed");
return -1;
}
receive = read(0, temp, N_INPUT);
if(receive < 0){
perror("Read stream: Failed!\n");
continue;
}
else if(receive == 0){
finish = 1;
for(i = 0; i < N_THREAD_READ; i++)
sem_post(&semaphore[0]);
break;
}
strcpy(buffer[ptr_write], temp);
ptr_write = (ptr_write + 1) % N_BUFFER;
if(sem_post(&semaphore[0]) != 0){
perror("Post semaphore0: Failed");
return -1;
}
}
puts("Reader finished");
for(i = 0; i < N_THREAD_READ; i++){
if(pthread_join(thread_array[i], NULL) != 0){
perror("Join thread: Failed");
}
}
return 0;
}
|
C
|
/*
***************************************************
PSPdisp (c) 2008 - 2009 Jochen Schleu
config.c - loading the config file
This software is licensed under the BSD license.
See license.txt for details.
***************************************************
*/
#include "config.h"
#define CONFIG_NAME "pspdisp.cfg"
/*
configLoadInteger
---------------------------------------------------
Read a value from the config file.
---------------------------------------------------
*/
void configLoadInteger(FILE* file, char* name, int* value, int defaultValue, int minValue, int maxValue)
{
*value = defaultValue;
if (file != NULL)
{
int found = 0;
int foundValue = 0;
char buffer[256];
char scanName[256];
fseek(file, 0, SEEK_SET);
strcpy(scanName, name);
strcat(scanName, " %d ");
while (!found)
{
if (fgets(buffer, 255, file) != NULL)
{
if (strlen(buffer) < 3)
continue;
found = sscanf(buffer, scanName, &foundValue);
}
else
break;
}
if (found)
{
if ((foundValue >= minValue) && (foundValue <= maxValue))
*value = foundValue;
}
}
DEBUG_PRINTF("configLoadInteger: name=%s, value=%d, defaultValue=%d, minValue=%d, maxValue=%d\n", name, *value, defaultValue, minValue, maxValue)
}
/*
configLoadString
---------------------------------------------------
Read a string from the config file.
---------------------------------------------------
*/
void configLoadString(FILE* file, char* name, char* value, char* defaultValue, int minLength, int maxLength)
{
strcpy(value, defaultValue);
if (file != NULL)
{
int found = 0;
char foundValue[256];
char buffer[256];
char scanName[256];
fseek(file, 0, SEEK_SET);
strcpy(scanName, name);
strcat(scanName, " \"%s\" ");
while (!found)
{
if (fgets(buffer, 255, file) != NULL)
{
if (strlen(buffer) < 3)
continue;
found = sscanf(buffer, scanName, &foundValue);
}
else
break;
}
if (found)
{
if ((strlen(foundValue) >= minLength) && (strlen(foundValue) <= maxLength + 1))
{
// omit trailing "
foundValue[strlen(foundValue) - 1] = 0;
strcpy(value, foundValue);
}
}
}
DEBUG_PRINTF("configLoadInteger: name=%s, value=%s, defaultValue=%s, minLength=%d, maxLength=%d\n", name, value, defaultValue, minLength, maxLength)
}
/*
configLoadConfiguration
---------------------------------------------------
Read the configuration.
---------------------------------------------------
*/
void configLoadConfiguration()
{
FILE *file;
file = fopen(CONFIG_NAME, "rt");
DEBUG_PRINTF("configLoadConfiguration: fileFound=%d", (file != NULL))
configLoadInteger(file, "usbSaveTimeout", &configUsbSaveTimeout, 5, 2, 3600);
configLoadInteger(file, "usbSave", &configUsbSave, 1, 0, 1);
configLoadInteger(file, "usbSaveScreenBacklight", &configUsbSaveScreenBacklight, 1, 0, 2);
configLoadInteger(file, "usbSaveClearScreen", &configUsbSaveClearScreen, 0, 0, 1);
configLoadInteger(file, "usbSaveDownClock", &configUsbSaveDownClock, 0, 0, 1);
configLoadInteger(file, "usbClockSpeed", &configUsbClockSpeed, 0, 0, 5);
configLoadInteger(file, "usbMode", &configUsbMode, 1, 0, 1);
configLoadInteger(file, "wlanClockSpeed", &configWlanClockSpeed, 0, 0, 5);
configLoadInteger(file, "wlanLedEnabled", &configWlanLedEnabled, 1, 0, 1);
configLoadInteger(file, "autoMode", &configAutoMode, 0, 0, 2);
configLoadInteger(file, "autoTimeout", &configAutoTimeout, 10, 0, 3600);
configLoadInteger(file, "wlanIPIndex", &configIpAddressIndex, 1, 1, 5);
configLoadString(file, "wlanPassword", configWlanPassword, "", 0, 32);
configLoadInteger(file, "wlanPortOffset", &configWlanPortOffset, 0, 0, 9);
configLoadInteger(file, "wlanEnableWakeOnLan", &configWlanWakeOnLanEnabled, 0, 0, 1);
configLoadInteger(file, "wlanEnableWakeOnLanBroadcasting", &configWlanWakeOnLanBroadcasting, 0, 0, 1);
// initialize the address array here
configLoadString(file, "wlanIPAddress1", configIpAddresses[0], "192.168.0.1", 0, 32);
configLoadString(file, "wlanIPAddress2", configIpAddresses[1], "192.168.0.1", 0, 32);
configLoadString(file, "wlanIPAddress3", configIpAddresses[2], "192.168.0.1", 0, 32);
configLoadString(file, "wlanIPAddress4", configIpAddresses[3], "192.168.0.1", 0, 32);
configLoadString(file, "wlanIPAddress5", configIpAddresses[4], "192.168.0.1", 0, 32);
configLoadString(file, "wlanMACAddress1", configMacAddresses[0], "00:00:00:00:00:00", 0, 17);
configLoadString(file, "wlanMACAddress2", configMacAddresses[1], "00:00:00:00:00:00", 0, 17);
configLoadString(file, "wlanMACAddress3", configMacAddresses[2], "00:00:00:00:00:00", 0, 17);
configLoadString(file, "wlanMACAddress4", configMacAddresses[3], "00:00:00:00:00:00", 0, 17);
configLoadString(file, "wlanMACAddress5", configMacAddresses[4], "00:00:00:00:00:00", 0, 17);
configLoadInteger(file, "brightness", &configBrightness, 100, 4, 100);
configLoadInteger(file, "setBrightness", &configAutosetBrightness, 0, 0, 1);
configLoadInteger(file, "buttonSwap", &configXOButtons, 0, 0, 2);
configLoadInteger(file, "timeFormat", &configTimeFormat, 0, 0, 2);
configLoadInteger(file, "verboseBattery", &configVerboseBattery, 1, 0, 1);
configLoadInteger(file, "transparentMenu", &configTransparentMenu, 1, 0, 1);
if (file != NULL)
fclose(file);
}
/*
configSaveInteger
---------------------------------------------------
Write an int value to the config file.
---------------------------------------------------
*/
void configSaveInteger(FILE* file, char* name, int* value)
{
fprintf(file, "%s %d\n", name, *value);
}
/*
configSaveString
---------------------------------------------------
Write a string to the config file.
---------------------------------------------------
*/
void configSaveString(FILE* file, char* name, char* value)
{
fprintf(file, "%s \"%s\"\n", name, value);
}
/*
configSaveConfiguration
---------------------------------------------------
Write the config fie.
---------------------------------------------------
*/
void configSaveConfiguration()
{
FILE *file;
file = fopen(CONFIG_NAME, "wt");
DEBUG_PRINTF("configSaveConfiguration: fileOpened=%d", (file != NULL))
configSaveInteger(file, "usbSaveTimeout", &configUsbSaveTimeout);
configSaveInteger(file, "usbSave", &configUsbSave);
configSaveInteger(file, "usbSaveScreenBacklight", &configUsbSaveScreenBacklight);
configSaveInteger(file, "usbSaveClearScreen", &configUsbSaveClearScreen);
configSaveInteger(file, "usbSaveDownClock", &configUsbSaveDownClock);
configSaveInteger(file, "usbClockSpeed", &configUsbClockSpeed);
configSaveInteger(file, "usbMode", &configUsbMode);
configSaveInteger(file, "wlanClockSpeed", &configWlanClockSpeed);
configSaveInteger(file, "wlanLedEnabled", &configWlanLedEnabled);
configSaveInteger(file, "autoMode", &configAutoMode);
configSaveInteger(file, "autoTimeout", &configAutoTimeout);
configSaveInteger(file, "wlanIPIndex", &configIpAddressIndex);
configSaveString(file, "wlanPassword", configWlanPassword);
configSaveInteger(file, "wlanEnableWakeOnLan", &configWlanWakeOnLanEnabled);
configSaveInteger(file, "wlanEnableWakeOnLanBroadcasting", &configWlanWakeOnLanBroadcasting);
configSaveInteger(file, "wlanPortOffset", &configWlanPortOffset);
// initialize the address array here
configSaveString(file, "wlanIPAddress1", configIpAddresses[0]);
configSaveString(file, "wlanIPAddress2", configIpAddresses[1]);
configSaveString(file, "wlanIPAddress3", configIpAddresses[2]);
configSaveString(file, "wlanIPAddress4", configIpAddresses[3]);
configSaveString(file, "wlanIPAddress5", configIpAddresses[4]);
configSaveString(file, "wlanMACAddress1", configMacAddresses[0]);
configSaveString(file, "wlanMACAddress2", configMacAddresses[1]);
configSaveString(file, "wlanMACAddress3", configMacAddresses[2]);
configSaveString(file, "wlanMACAddress4", configMacAddresses[3]);
configSaveString(file, "wlanMACAddress5", configMacAddresses[4]);
configSaveInteger(file, "brightness", &configBrightness);
configSaveInteger(file, "setBrightness", &configAutosetBrightness);
configSaveInteger(file, "buttonSwap", &configXOButtons);
configSaveInteger(file, "timeFormat", &configTimeFormat);
configSaveInteger(file, "verboseBattery", &configVerboseBattery);
configSaveInteger(file, "transparentMenu", &configTransparentMenu);
fclose(file);
}
|
C
|
//Primera parte se incluyen las librerias tanto del sistema, como hecha por nosotros
#include <stdio.h>
#include <stdlib.h>
//La funcion Principal
int main (){
int variable1 = 0;
float variable2 =0;
char miprimercaracter;
printf("Usuario porfavor ingrese un numero: ");
scanf("%d",&variable1);
printf("Lo que ingresaste fue: %d\n",variable1);
printf("Usuario porfavor ingrese un numero con punto decimal: ");
scanf("%f",&variable2);
printf("Lo que ingresaste fue: %f\n",variable2);
printf("Ingresa un caracter porfavor: ");
fflush(stdin);
scanf("%c",&miprimercaracter);
printf("El caracter ingresado es: %d\n\n",miprimercaracter);
system("PAUSE");
//Saludos de parte de Richi
printf ("hola como estan ");
return 0;
}
|
C
|
//Fbio Henrique Alves Fernandes
//19.1.4128
//Turma 64
#include <stdio.h>
int main(){
double prova1[15], prova2[15], media[15];
printf ("Prova 1\n");
for (int i = 0; i < 15; i++){
printf ("Aluno %d: ", i+1);
scanf ("%lf", &prova1[i]);
}
printf ("Prova 2\n");
for (int i = 0; i < 15; i++){
printf ("Aluno %d: ", i+1);
scanf ("%lf", &prova2[i]);
}
//Tirar a media
for (int i = 0; i < 15; i++){
media[i] = (prova1[i] + prova2[i])/2.0;
if (media[i] >= 60.0)
printf ("Aluno %d Aprovado com %.1lf de media\n", i+1, media[i]);
else
printf ("Aluno %d Reprovado com %.1lf de media\n", i+1, media[i]);
}
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2019
** my_strstr
** File description:
** make the my_strstr
*/
#include <unistd.h>
int compare_the_string(int i, char *str, char const *to_find)
{
int j = 0;
for (int n = i; str[n] == to_find[j] && str[n] != '\0'; n++) {
j++;
if (to_find[j] == '\0')
return (i);
}
return (0);
}
char *my_strstr(char *str, char const *to_find)
{
int i;
int find;
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == to_find[0]) {
find = compare_the_string(i, str, to_find);
if (find > 0)
return (&(str[i]));
}
}
return (NULL);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUMBER_OF_CUSTOMERS 5
#define NUMBER_OF_RESOURCES 4
/* the available amount of each resource */
int available[NUMBER_OF_RESOURCES];
/*the maximum demand of each customer */
int maximum[NUMBER_OF_CUSTOMERS][NUMBER_OF_RESOURCES];
/* the amount currently allocated to each customer */
int allocation[NUMBER_OF_CUSTOMERS][NUMBER_OF_RESOURCES];
/* the remaining need of each customer */
int need[NUMBER_OF_CUSTOMERS][NUMBER_OF_RESOURCES];
// print a vector
void print_vector(int v[NUMBER_OF_RESOURCES])
{
int i;
for(i=0; i<NUMBER_OF_RESOURCES; i++)
printf("%d ", v[i]);
printf("\n");
}
// print a matrix
void print_matrix(int m[NUMBER_OF_CUSTOMERS][NUMBER_OF_RESOURCES])
{
int i, j;
for(i=0; i<NUMBER_OF_CUSTOMERS; i++)
{
for(j=0; j<NUMBER_OF_RESOURCES; j++)
printf("%d ", m[i][j]);
printf("\n");
}
}
// copy vector
void v_cpy(int *dst, int *src){
int i;
for(i=0; i<NUMBER_OF_RESOURCES; i++)
dst[i] = src[i];
}
// add vector
void v_add(int *dst, int *src, int sgn){
int i;
for(i=0; i<NUMBER_OF_RESOURCES; i++)
dst[i] += src[i] * sgn;
}
// compare vector
int v_leq(int *left, int *right){
int i;
int flag = 0;
for(i=0; i<NUMBER_OF_RESOURCES; i++)
flag += (left[i] <= right[i]);
return (flag == NUMBER_OF_RESOURCES);
}
// safety algorithm
// return 1 if safe, 0 if unsafe
int safety(){
int work[NUMBER_OF_RESOURCES];
int finished = 0;
int i, flag = 1;
v_cpy(work, available);
do{
if(!flag) return 0;
flag = 0;
for(i=0; i<NUMBER_OF_CUSTOMERS; i++){
if(!(finished & (1 << i)) && v_leq(need[i], work)){
flag = 1;
v_add(work, allocation[i], 1);
finished = (finished | (1 << i));
}
}
}while(finished != (1<<(NUMBER_OF_CUSTOMERS)) - 1);
return 1;
}
// update resources
void _resources_change(int customer_num, int release[], int sgn){
v_add(available, release, sgn);
v_add(allocation[customer_num], release, -sgn);
v_add(need[customer_num], release, sgn);
}
// request resources
int request_resources(int customer_num, int request[]){
int flag;
if(!v_leq(request, need[customer_num]))
{
printf("request exceeds need\n");
return -1;
}
if(!v_leq(request, available))
{
printf("request denied due to limited resource\n");
return -1;
}
_resources_change(customer_num, request, -1);
if(safety()) return 0;
_resources_change(customer_num, request, 1);
printf("request denied due to deadlock\n");
return -1;
}
// release resources
void release_resources(int customer_num, int release[]){
_resources_change(customer_num, release, 1);
}
int main(int argc, char **args){
FILE *file = fopen("maximum.txt", "r");
// FILE *filea = fopen("allocation.txt", "r"); // for quick test
int i, j;
int request[NUMBER_OF_RESOURCES];
char s[3];
for(i=0; i<NUMBER_OF_CUSTOMERS; i++){
for(j=0; j<NUMBER_OF_RESOURCES; j++){
fscanf(file, ((j==NUMBER_OF_RESOURCES-1)?"%d\n":"%d,"), &maximum[i][j]);
// fscanf(filea, ((j==NUMBER_OF_RESOURCES-1)?"%d\n":"%d,"), &allocation[i][j]); // for quick test
allocation[i][j] = 0;
need[i][j] = maximum[i][j];
// need[i][j] = maximum[i][j] - allocation[i][j]; // for quick test
}
}
fclose(file);
// fclose(filea); // for quick test
for(j=0; j<NUMBER_OF_RESOURCES; j++)
available[j] = ((j<argc-1)?atoi(args[j+1]):0);
while(1){
scanf("%s", s);
if(s[0] == '*'){
printf("available:\n");
print_vector(available);
printf("maximum:\n");
print_matrix(maximum);
printf("allocation:\n");
print_matrix(allocation);
printf("need:\n");
print_matrix(need);
}
else{
scanf("%d", &j);
for(i=0; i<NUMBER_OF_RESOURCES; i++)
scanf("%d", &request[i]);
if(s[1] == 'Q' || s[1] == 'q'){
if(request_resources(j, request) == 0){
printf("request satisfied\n");
}
}
else if(s[1] == 'L' || s[1] == 'l'){
if(v_leq(request, allocation[j])){
release_resources(j, request);
printf("resources released\n");
}
else{
printf("release exceeds allocation\n");
}
}
else{
printf("unkown command\n");
}
}
}
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
int Factorial(int);
int main()
{
int No=0;
printf("\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n");
printf("\n Enter Number To Find Factorial = ");
scanf("%d",&No);
printf("\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n");
printf("\n Factorial of %d is = %d \n", No,Factorial(No));
printf("\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n");
getch();
return 0;
}
int Factorial(int Num)
{
int Fact = 1 ;
if(Num > 0)
{
return Num * Factorial(Num-1);
}
else
{
return Fact;
}
}
|
C
|
#include "simp.h"
int * add_1_svc(operands * argp, struct svc_req * rqstp) {
static int result;
printf("Got request: adding %d,%d\n", argp -> x, argp -> y);
result = argp -> x + argp -> y;
return ( &result);
}
int * sub_1_svc(operands * argp, struct svc_req * rqstp) {
static int result;
printf("Got request:subtracting %d,%d\n", argp -> x, argp -> y);
result = argp -> x - argp -> y;
return ( &result);
}
|
C
|
/**************************************************************************
* FILE : sample_to_show_simultaneous_task_by_main_and_thread().c
* DESCRIPTION : Program to demonstrate simultaneous task by main thread
* i.e addition of two number and created thread i.e subtraction
* of two number.
* AUTHOR : GALDSON HANSDA
* DATED : 20/07/2020
* ***********************************************************************/
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
void* Addition(void* arg)
{
sleep(2);
long sum=0;
//args = *(long*)arg;
for(long i=0;i<10;i++)
{
sum+=i;
}
printf("Addition of these numbers are: %ld\n",sum);
pthread_exit(NULL);
}
int main()
{
pthread_t thread;
int rc;
long t=0;
rc = pthread_create(&thread,NULL,Addition,(void*)t);
if(rc)
{
printf("ERROR; return code from pthread_create() is %d\n",rc);
exit(-1);
}
printf("Number from digit 1 to 10 are: \n");
for(t=0;t<10;t++)
{
printf("%ld\n",t);
}
pthread_join(thread,NULL);
pthread_exit(NULL);
return 0;
}
|
C
|
/*********************************************************************************
Name: Parthesh Soni Roll No.:16BIT015
Practical No.: 7(a) Topic: Change the case of the Inputted Sentence
DOS: DOC:
*********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str[1000];
int code, i;
printf("Enter your statement:");
gets(str);
printf("\nChoose the code of the transformation you want to perform:\n1> Title Case\n2> UPPER CASE\n3> lower case\n4> Sentence Case");
enter:
printf("\n\nEnter a valid code:");
scanf("%d", &code);
switch(code)
{
case 1:
for(i=0; str[i]!='\0'; i++)
{
if(i==0)
str[i]=toupper(str[i]);
if((str[i]==' '|| str[i]==',') && isalpha(str[i+1]))
str[i+1]=toupper(str[i+1]);
}
break;
case 2:
for(i=0; str[i]!='\0'; i++)
{
str[i]=toupper(str[i]);
}
break;
case 3:
for(i=0; str!='\0'; i++)
{
str[i]=tolower(str[i]);
}
break;
case 4:
str[0]=toupper(str[0]);
break;
default:
printf("\nPlease enter a valid code!\n");
goto enter;
}
printf("\nThe statement of your given choice is as follows:\n\"%s\"\n\n", str);
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
//Declare variables.
int i=0;
/*
loop
*/
int x=0;
/* This is a /*nested comment*/
for(i=0; i<10; ++i)
printf("loop\n");
//One more comment.
/*
One more multi-line comment.*/
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main() {
char* binsh = "/bin/sh";
printf("%p\n",system);
printf("%p\n",binsh);
char buffer[100];
printf("Enter some input!\n");
gets(buffer);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: oel-ahma <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/06/23 12:44:27 by oel-ahma #+# #+# */
/* Updated: 2019/06/23 19:26:57 by oel-ahma ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
int ft_isspace(char c)
{
return (c == ' ' || c == '\n' || c == '\t' || c == ':'
|| (c >= '0' && c <= '9'));
}
int count_words(char *str)
{
int count;
count = 0;
while (*str)
{
while (*str && ft_isspace(*str))
str++;
if (*str && !ft_isspace(*str))
{
count++;
while (*str && !ft_isspace(*str))
str++;
}
}
return (count);
}
char *malloc_word(char *str)
{
char *word;
int i;
i = 0;
while (str[i] && !ft_isspace(str[i]))
i++;
word = malloc(sizeof(char) * (i + 1));
i = 0;
while (str[i] && str[i] != '\n')
{
word[i] = str[i];
i++;
}
word[i] = '\0';
return (word);
}
char **ft_split(char *str)
{
char **arr;
int i;
arr = malloc(sizeof(char *) * (count_words(str) + 1));
i = 0;
while (*str)
{
while (*str && ft_isspace(*str))
str++;
if (*str && !ft_isspace(*str))
{
arr[i] = malloc_word(str);
i++;
while (*str && !ft_isspace(*str))
str++;
}
}
arr[i] = NULL;
return (arr);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "../../../MyLibraries/STD_TYPES.h"
#include "Deque_DLL.h"
// does the initialization got any bad effects ?!
// or should i create an initialization function ??
static DNode_t* Rear, *Front;
void Deque_Init(void)
{
Front = NULL;
Rear =NULL;
}
u8 Deque_IsEmpty(void)
{
u8 ErrorState = OK;
if (Front == NULL)
{
}
else
{
ErrorState = NOK;
}
return ErrorState;
}
u8 InsertAtEmpty(s32 Data)
{
u8 ErrorState = OK;
DNode_t* Temp = (DNode_t*)malloc(sizeof(DNode_t));
if (Temp == NULL)
{
printf("No memory to allocate your insertion\n\n");
ErrorState = NOK;
}
else
{
Temp->Info = Data;
Temp->prev = NULL;
Temp->next = NULL;
Front = Temp;
Rear = Temp;
printf("Insertion of 1st element in the deque is done\n\n");
}
return ErrorState;
}
u8 InsertAtBeginning(s32 Data)
{
u8 ErrorState = OK;
if (Deque_IsEmpty())
{
InsertAtEmpty(Data);
}
else
{
DNode_t* Temp = (DNode_t*)malloc(sizeof(DNode_t));
if (Temp == NULL)
{
printf("No memory to allocate your insertion\n\n");
ErrorState = NOK;
}
else
{
Temp->Info = Data;
Temp->prev = NULL;
Temp->next = Front;
Front->prev = Temp;
Front = Temp;
printf("Insertion at beginning is done successfully\n\n");
}
}
return ErrorState;
}
u8 InsertAtEnd(s32 Data)
{
u8 ErrorState = OK;
if (Deque_IsEmpty())
{
InsertAtEmpty(Data);
}
else
{
DNode_t* Temp = (DNode_t*)malloc(sizeof(DNode_t));
if (Temp == NULL)
{
printf("No memory to allocate your insertion\n\n");
ErrorState = NOK;
}
else
{
Temp->Info = Data;
Temp->next = NULL;
Temp->prev = Rear;
Rear->next = Temp;
Rear = Temp;
printf("Insertion at the end is done successfully\n\n");
}
}
return ErrorState;
}
u8 DeleteOnlyNode(s32* DataPtr)
{
u8 ErrorState = OK;
if ((Front==Rear)&&(Front!=NULL))
{
*DataPtr = Front->Info;
DNode_t* Temp = Front;
free(Temp);
Front = NULL;
Rear = NULL;
printf("Deletion of only existing element\n");
}
else
{
ErrorState = NOK;
}
return ErrorState;
}
u8 DeleteAtBeginning(s32* DataPtr)
{
u8 ErrorState = OK;
if (DataPtr == NULL)
{
ErrorState = NOK;
}
else if (Deque_IsEmpty())
{
printf("Deque is totally empty\n\n");
}
else if (DeleteOnlyNode(DataPtr))
{
//Do nothing
}
else
{
*DataPtr = Front->Info;
DNode_t* Temp = Front;
Front = Temp->next;
Temp->next->prev = NULL;
free(Temp);
printf("Deletion from beginning is done successfully\n\n");
}
return ErrorState;
}
u8 DeleteAtEnd(s32* DataPtr)
{
u8 ErrorState = OK;
if (DataPtr == NULL)
{
ErrorState = NOK;
}
else if (Deque_IsEmpty())
{
printf("Deque is totally empty\n\n");
}
else if (DeleteOnlyNode(DataPtr))
{
//Do nothing
}
else
{
*DataPtr = Rear->Info;
DNode_t* Temp = Rear;
Rear = Temp->prev;
Temp->prev->next = NULL;
free(Temp);
printf("Deletion from end is done successfully\n\n");
}
return ErrorState;
}
void DisplayDeque(void)
{
//check if empty\n\n
if (Deque_IsEmpty())
{
printf("Deque is totally empty\n\n");
}
else
{
printf("The Deque is: \n");
DNode_t* ptr = Front;
while (ptr!=NULL)
{
printf("%d\t", ptr->Info);
ptr=ptr->next;
}
printf("\n\n");
}
}
|
C
|
#include <stdio.h>
#include <string.h>
#define STR_MAX 100
#define MAX_NODE 500001
// m[h^`
typedef struct _NODE{
int key;
struct _NODE *right;
struct _NODE *left;
} NODE;
// m[hpRAMǗ
NODE node_pool[MAX_NODE];
int node_cnt;
NODE *make_node(int key);
void release_node(NODE *node);
// c[
NODE *insert_node(NODE *root,int k);
void print_tree(NODE *root);
void print_tree_inorder(NODE *node);
void print_tree_preorder(NODE *node);
NODE *find_node(NODE *root,int k);
void delete_node(NODE **root,int k);
/////////////////////////////
// C
int main(){
int i;
int m,k;
NODE *root;
char buf[STR_MAX];
node_cnt = 0;
root = NULL;
// ߐǂݍŃ[v
scanf("%d%*c",&m);
for( i=0; i<m; i++){
// ߂ǂݍŏ
fgets(buf,STR_MAX,stdin);
if(strncmp(buf,"insert",6)==0){
// insert
sscanf(buf,"%*s %d",&k);
root = insert_node(root,k);
}else if(strncmp(buf,"print",5)==0){
// print
print_tree(root);
}else if(strncmp(buf,"find",4)==0){
// find
sscanf(buf,"%*s %d",&k);
if(find_node(root,k)==NULL){
printf("no\n");
}else{
printf("yes\n");
}
}else if(strncmp(buf,"delete",6)==0){
// delete
sscanf(buf,"%*s %d",&k);
delete_node(&root,k);
}else{
//Ȃ
}
}
return 0;
}
/////////////////////////////
// c[
// vflj
// c[̃[gԂ
NODE *insert_node(NODE *root,int k){
NODE *new_root = root;
NODE *y = NULL; // x ̐e
NODE *x = root;
NODE *z = make_node(k);
while( x != NULL ){
y = x; // eݒ
if( z->key < x->key ){
x = x->left; // ̎qֈړ
}else{
x = x->right; // E̎qֈړ
}
}
if( y == NULL){ // T ̏ꍇ
new_root = z;
}else if( z->key < y->key){
y->left = z; // z y ̍̎qɂ
}else{
y->right = z; // z y ̉E̎qɂ
}
return new_root;
}
// e\
void print_tree(NODE *root){
print_tree_inorder(root);
printf("\n");
print_tree_preorder(root);
printf("\n");
}
// ԏ
void print_tree_inorder(NODE *node){
if(node==NULL) return;
print_tree_inorder(node->left);
printf(" %d",node->key);
print_tree_inorder(node->right);
}
// s
void print_tree_preorder(NODE *node){
if(node==NULL) return;
printf(" %d",node->key);
print_tree_preorder(node->left);
print_tree_preorder(node->right);
}
// w̃L[̃m[hԂ
// ȂNULLԂ
NODE *find_node(NODE *root,int k){
NODE *next;
if(root == NULL) return NULL;
if(root->key == k) return root;
if(root->key < k){
next = root->right;
}else{
next = root->left;
}
return find_node(next,k);
}
// w̃L[̃m[h폜
void delete_node(NODE **root,int k){
NODE **ref;
ref = root;
while( (*ref != NULL) && ((*ref)->key != k) ){
if((*ref)->key < k){
ref = &((*ref)->right);
}else{
ref = &((*ref)->left);
}
}
while(*ref != NULL){
if( (*ref)->left != NULL ){
(*ref)->key = (*ref)->left->key;
ref = &((*ref)->left);
}else if( (*ref)->right != NULL ){
(*ref)->key = (*ref)->right->key;
ref = &((*ref)->right);
}else{
release_node(*ref);
*ref = NULL;
}
}
}
//////////////////////
//m[hpRAMǗ
//VKm[h쐬
NODE *make_node(int key){
NODE *node = &node_pool[node_cnt];
node_cnt++;
node->key = key;
node->right = NULL;
node->left = NULL;
return node;
}
//m[h폜ij
void release_node(NODE *node){
}
|
C
|
/*
* main.c
*
* Created on: 17 mars 2020
* Author: pvgmenegasso
*
https://www.urionlinejudge.com.br/judge/en/problems/view/1168
John wants to set up a panel containing different numbers of LEDs. He does not have many leds,
he is not sure if he will be able to mount the desired number. Considering the configuration of
the LEDs of the numbers below, make an algorithm that helps John to discover the number of LEDs
needed to set the value.
Input
The input contains an integer N, (1 ≤ N ≤ 2000) corresponding to the number of test cases,
followed by N lines, each line containing a number (1 ≤ V ≤ 10100) corresponding to the value
that John wants to set with the leds.
Output
For each test case, print one line containing the number of LEDs that John needs to set the desired value,
followed by the word "leds".
Input Sample output sample
27 leds
3 29 leds
115380 25 leds
2819311
23456
*/
#include <stdlib.h>
#include <stdio.h>
int chartoleds(char c)
{
switch (c)
{
case '1':
return 2 ;
break;
case '2':
return 5 ;
break;
case '3':
return 5 ;
break;
case '4':
return 4 ;
break;
case '5':
return 5 ;
break;
case '6':
return 6 ;
break;
case '7':
return 3;
break;
case '8':
return 7 ;
break;
case '9':
return 6 ;
break;
case '0':
return 6 ;
break;
}
return 0 ;
}
int ledstostring(char str[])
{
int i = 0 ;
int value = 0 ;
while(str[i] != '\0')
{
value += chartoleds(str[i]) ;
i++ ;
}
return value ;
}
int main(void)
{
printf("%d", ledstostring("23456")) ;
return 0 ;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_6__ TYPE_2__ ;
typedef struct TYPE_5__ TYPE_1__ ;
/* Type definitions */
typedef int /*<<< orphan*/ sqlite3_int64 ;
struct TYPE_6__ {int nSegment; TYPE_1__** apSegment; } ;
struct TYPE_5__ {int iIdx; scalar_t__ aNode; char* zTerm; int nTerm; } ;
typedef int /*<<< orphan*/ Fts3Table ;
typedef TYPE_1__ Fts3SegReader ;
typedef TYPE_2__ Fts3MultiSegReader ;
/* Variables and functions */
scalar_t__ ALWAYS (int) ;
int SQLITE_OK ;
int /*<<< orphan*/ assert (int) ;
int fts3DeleteSegment (int /*<<< orphan*/ *,TYPE_1__*) ;
int fts3RemoveSegdirEntry (int /*<<< orphan*/ *,int /*<<< orphan*/ ,int) ;
int fts3RepackSegdirLevel (int /*<<< orphan*/ *,int /*<<< orphan*/ ) ;
int fts3TruncateSegment (int /*<<< orphan*/ *,int /*<<< orphan*/ ,int,char const*,int) ;
__attribute__((used)) static int fts3IncrmergeChomp(
Fts3Table *p, /* FTS table handle */
sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
int *pnRem /* Number of segments not deleted */
){
int i;
int nRem = 0;
int rc = SQLITE_OK;
for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
Fts3SegReader *pSeg = 0;
int j;
/* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
** somewhere in the pCsr->apSegment[] array. */
for(j=0; ALWAYS(j<pCsr->nSegment); j++){
pSeg = pCsr->apSegment[j];
if( pSeg->iIdx==i ) break;
}
assert( j<pCsr->nSegment && pSeg->iIdx==i );
if( pSeg->aNode==0 ){
/* Seg-reader is at EOF. Remove the entire input segment. */
rc = fts3DeleteSegment(p, pSeg);
if( rc==SQLITE_OK ){
rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
}
*pnRem = 0;
}else{
/* The incremental merge did not copy all the data from this
** segment to the upper level. The segment is modified in place
** so that it contains no keys smaller than zTerm/nTerm. */
const char *zTerm = pSeg->zTerm;
int nTerm = pSeg->nTerm;
rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
nRem++;
}
}
if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
rc = fts3RepackSegdirLevel(p, iAbsLevel);
}
*pnRem = nRem;
return rc;
}
|
C
|
#include "list.h"
#include "file_util.h"
void
remove_carriage_return_from_string(char *str) {
char *pos = NULL;
if ( (pos = strchr( str, '\n' )) != NULL ) *pos = '\0';
}
/**
Read a string from stdin
@param message: a message to display for a user
*/
char*
reader( char *message ) {
char *str = NULL;
char aux[STRING_MAX];
printf("%s: ", message);
__fpurge(stdin);
fgets(aux, STRING_MAX, stdin);
remove_carriage_return_from_string(aux);
size_t str_lenght = strlen(aux);
str = malloc(sizeof(char) * str_lenght);
strncpy(str, aux, str_lenght);
return str;
}
/**
Read a number (formated string) from stdin
@param message: a message to display for a user
*/
int
num_reader( char *message ) {
int number;
printf("%s: ", message);
__fpurge(stdin); //wait for the prompt to be written on the screen
scanf("%d",&number);
return number;
}
static int
display(void) {
printf(":=============================================================:\n"
"| ANAC - Airports management and air control system. |\n"
"| 1 - Register airport. |\n"
"| 2 - Remove airport. |\n"
"| 3 - List all registered airports. |\n"
"| 4 - Register flight. |\n"
"| 5 - Delete flight. |\n"
"| 6 - Interactive travel. |\n"
"| 7 - Export file. |\n"
"| 8 - Import flie. |\n"
"| 0 - Exit. |\n"
":=============================================================:\n");
printf("$ ");
return num_reader("Type an option: ");
}
int
main(int argc, char const *argv[]) {
airports *airports_list = airports_list_new();
char *filename = NULL;
int option = 1;
while(option) {
option = display();
switch(option) {
case 1:
collect_airport_data(airports_list);
break;
case 2:
remove_airport_data(airports_list);
break;
case 3:
list_and_show_airports_with_flights(airports_list);
break;
case 4:
find_airport_and_create_a_fligth(airports_list);
break;
case 5:
remove_a_flight_from_airport_get_uuid(airports_list);
break;
case 6:
if(airports_list->length == 0){
printf("No airports\n" );
break;
}
interactive_travel(airports_list);
break;
case 7:
list_to_stream(airports_list);
break;
case 8:
filename = reader( "Type the file name: " );
import_from_file(filename, airports_list);
break;
}
}
destroy_airports_list(airports_list);
return 0;
}
|
C
|
#include<stdio.h>
void toplama()
{
int a,b,toplam;
printf("1.sayiyi giriniz");
scanf("%d",&a);
printf("2.sayiyi giriniz");
scanf("%d",&b);
toplam=a+b;
printf("Toplam=%d",toplam);
}
int main()
{
toplama();
}
|
C
|
/*
** EPITECH PROJECT, 2020
** NWP_myteams_2019
** File description:
** commands4
*/
#include "client.h"
void teamlist_receive(char **args, CLI_DATA *data)
{
(void) data;
client_print_teams(args[1], args[2], args[3]);
if (how_many_words(args) > 4)
teamlist_receive(&args[4], data);
}
void chanlist_receive(char **args, CLI_DATA *data)
{
(void) data;
client_team_print_channels(args[1], args[2], args[3]);
if (how_many_words(args) > 4)
chanlist_receive(&args[4], data);
}
void threadlist_receive(char **args, CLI_DATA *data)
{
(void) data;
client_channel_print_threads(args[1], args[2], atol(args[3]),
args[4], args[5]);
if (how_many_words(args) > 6)
threadlist_receive(&args[6], data);
}
void replylist_receive(char **args, CLI_DATA *data)
{
(void) data;
client_thread_print_replies(args[1], args[2], atol(args[3]), args[4]);
if (how_many_words(args) > 5)
threadlist_receive(&args[5], data);
}
|
C
|
#include <stdio.h>
int pascal[1003][1003];
long long now;
const long long mod=1e9+7;
int i,j;
int main(){
for(i=2,pascal[1][1]=1;i<=1000;i++)
for(j=2,pascal[i][1]=1;j<=i;j++){
now=(long long)pascal[i-1][j]+pascal[i-1][j-1];
pascal[i][j]=now%mod;
}
while(scanf("%d",&i)>0){
for(j=1;j<=i;j++)
printf("%d ",pascal[i][j]);
printf("\n");
}
return 0;
}
|
C
|
/**
* @file nninterpcli.c
* @brief Nearest neighbor image interpolation utility
* @author Pascal Getreuer <getreuer@gmail.com>
*
*
* Copyright (c) 2010-2011, Pascal Getreuer
* All rights reserved.
*
* This program is free software: you can use, modify and/or
* redistribute it under the terms of the simplified BSD License. You
* should have received a copy of this license along this program. If
* not, see <http://www.opensource.org/licenses/bsd-license.html>.
*/
#include <math.h>
#include <string.h>
#include <ctype.h>
#include "nninterp.h"
#define VERBOSE 0
/** @brief struct representing an image */
typedef struct
{
/** @brief 32-bit RGBA image data */
uint32_t *Data;
/** @brief Image width */
int Width;
/** @brief Image height */
int Height;
} image;
/** @brief struct of program parameters */
typedef struct
{
/** @brief Input file name */
char *InputFile;
/** @brief Output file name */
char *OutputFile;
/** @brief Quality for saving JPEG images (0 to 100) */
int JpegQuality;
/** @brief If true, sample on the centered grid */
int CenteredGrid;
/** @brief Scale factor */
float ScaleFactor;
} programparams;
int ParseParams(programparams *Param, int argc, char *argv[]);
/** @brief Print program usage help message */
void PrintHelpMessage()
{
puts("Nearest neighbor interpolation utility, P. Getreuer 2011\n");
puts("Usage: iminterpnn [options] <input file> <output file>\n"
"Only " READIMAGE_FORMATS_SUPPORTED " images are supported.\n");
puts("Options:\n");
puts(" -x <number> the interpolation factor\n");
puts(
" -g <grid> grid to use for resampling, choices for <grid> are\n"
" centered grid with centered alignment (default)\n"
" topleft the top-left anchored grid\n");
#ifdef USE_LIBJPEG
puts(" -q <number> quality for saving JPEG images (0 to 100)\n");
#endif
puts("Example: interpolate by factor 2.5\n"
" iminterpnn -x 2.5 frog.bmp coarse.bmp");
}
int main(int argc, char *argv[])
{
programparams Param;
image u = {NULL, 0, 0}, v = {NULL, 0, 0};
int Status = 1;
if(!ParseParams(&Param, argc, argv))
return 0;
/* Read the input image */
if(!(v.Data = (uint32_t *)ReadImage(&v.Width, &v.Height, Param.InputFile,
IMAGEIO_U8 | IMAGEIO_RGBA)))
goto Catch;
/* Allocate the output image */
u.Width = (int)ceil(v.Width * Param.ScaleFactor);
u.Height = (int)ceil(v.Height * Param.ScaleFactor);
#if VERBOSE > 0
printf("%dx%d input --> %dx%d output\n", v.Width, v.Height, u.Width, u.Height);
#endif
if(!(u.Data = (uint32_t *)Malloc(sizeof(uint32_t)*
((long int)u.Width)*((long int)u.Height))))
{
fprintf(stderr, "Memory allocation failed.\n");
goto Catch;
}
NearestInterp(u.Data, u.Width, u.Height,
v.Data, v.Width, v.Height,
Param.ScaleFactor, Param.CenteredGrid);
/* Write the output image */
if(!WriteImage(u.Data, u.Width, u.Height, Param.OutputFile,
IMAGEIO_U8 | IMAGEIO_RGBA, Param.JpegQuality))
goto Catch;
#if VERBOSE > 0
else
printf("Output written to \"%s\".\n", Param.OutputFile);
#endif
Status = 0; /* Finished successfully, set exit status to zero. */
Catch:
Free(u.Data);
Free(v.Data);
return Status;
}
int ParseParams(programparams *Param, int argc, char *argv[])
{
static char *DefaultOutputFile = (char *)"out.bmp";
char *OptionString;
char OptionChar;
int i;
if(argc < 2)
{
PrintHelpMessage();
return 0;
}
/* Set parameter defaults */
Param->InputFile = 0;
Param->OutputFile = DefaultOutputFile;
Param->JpegQuality = 99;
Param->ScaleFactor = 1;
Param->CenteredGrid = 1;
for(i = 1; i < argc;)
{
if(argv[i] && argv[i][0] == '-')
{
if((OptionChar = argv[i][1]) == 0)
{
ErrorMessage("Invalid parameter format.\n");
return 0;
}
if(argv[i][2])
OptionString = &argv[i][2];
else if(++i < argc)
OptionString = argv[i];
else
{
ErrorMessage("Invalid parameter format.\n");
return 0;
}
switch(OptionChar)
{
case 'x':
Param->ScaleFactor = (float)atof(OptionString);
if(Param->ScaleFactor < 0)
{
ErrorMessage("Invalid scale factor.\n");
return 0;
}
break;
case 'g':
if(!strcmp(OptionString, "centered")
|| !strcmp(OptionString, "center"))
Param->CenteredGrid = 1;
else if(!strcmp(OptionString, "topleft")
|| !strcmp(OptionString, "top-left"))
Param->CenteredGrid = 0;
else
{
ErrorMessage("Grid must be either \"centered\" or \"topleft\".\n");
return 0;
}
break;
#ifdef USE_LIBJPEG
case 'q':
Param->JpegQuality = atoi(OptionString);
if(Param->JpegQuality <= 0 || Param->JpegQuality > 100)
{
ErrorMessage("JPEG quality must be between 0 and 100.\n");
return 0;
}
break;
#endif
case '-':
PrintHelpMessage();
return 0;
default:
if(isprint(OptionChar))
ErrorMessage("Unknown option \"-%c\".\n", OptionChar);
else
ErrorMessage("Unknown option.\n");
return 0;
}
i++;
}
else
{
if(!Param->InputFile)
Param->InputFile = argv[i];
else
Param->OutputFile = argv[i];
i++;
}
}
if(!Param->InputFile)
{
PrintHelpMessage();
return 0;
}
return 1;
}
|
C
|
#include <stdio.h>
int main(void)
{
double balance, deposit = 1000, rate = 0.05;
int year = 0;
while( balance < 10000000)
{
balance *= 1/05;
year++;
}
printf("It takes %d years to have $1,000,000.00.\n", year);
}
|
C
|
void order(int m,int n)
{ int i,s[100];
for(i=0;i<m;i++)
scanf("%d",&s[i]);
for(i=m-n;i<m;i++)
printf("%d ",s[i]);
for(i=0;i<m-n-1;i++)
printf("%d ",s[i]);
printf("%d",s[i]);
}
main()
{ int a,b;
scanf("%d %d",&a,&b);
order(a,b);
}
|
C
|
#include "ccv.h"
#include "case.h"
TEST_CASE("matrix multiplication")
{
ccv_dense_matrix_t* a = ccv_dense_matrix_new(3, 2, CCV_64F | CCV_C1, 0, 0);
a->data.f64[0] = 0.11;
a->data.f64[1] = 0.12;
a->data.f64[2] = 0.13;
a->data.f64[3] = 0.21;
a->data.f64[4] = 0.22;
a->data.f64[5] = 0.23;
ccv_dense_matrix_t* b = ccv_dense_matrix_new(3, 2, CCV_64F | CCV_C1, 0, 0);
b->data.f64[0] = 1011;
b->data.f64[1] = 1012;
b->data.f64[2] = 1021;
b->data.f64[3] = 1022;
b->data.f64[4] = 1031;
b->data.f64[5] = 1032;
ccv_dense_matrix_t* y = 0;
ccv_gemm(a, b, 1, 0, 0, CCV_A_TRANSPOSE, (ccv_matrix_t**)&y, 0);
double hy[4] = {470.760000, 471.220000, 572.860000, 573.420000};
REQUIRE_ARRAY_EQ_WITH_TOLERANCE(double, hy, y->data.f64, 4, 1e-6, "2x3, 3x2 matrix multiplication failure");
ccv_matrix_free(a);
ccv_matrix_free(b);
ccv_matrix_free(y);
}
TEST_CASE("vector sum")
{
ccv_dense_matrix_t* a = ccv_dense_matrix_new(3, 2, CCV_64F | CCV_C1, 0, 0);
a->data.f64[0] = 0.11;
a->data.f64[1] = 0.12;
a->data.f64[2] = 0.13;
a->data.f64[3] = 0.21;
a->data.f64[4] = 0.22;
a->data.f64[5] = 0.23;
double sum = ccv_sum(a, CCV_SIGNED);
ccv_matrix_free(a);
REQUIRE_EQ_WITH_TOLERANCE(sum, 1.02, 1e-6, "3x2 vector sum failure");
}
TEST_CASE("vector L2 normalize")
{
int i;
ccv_dense_matrix_t* dmt = ccv_dense_matrix_new(1, 10, CCV_32F | CCV_C1, 0, 0);
for (i = 0; i < 10; i++)
dmt->data.f32[i] = i;
ccv_normalize(dmt, (ccv_matrix_t**)&dmt, 0, CCV_L2_NORM);
float hm[10] = {0.000000, 0.059235, 0.118470, 0.177705, 0.236940, 0.296174, 0.355409, 0.414644, 0.473879, 0.533114};
REQUIRE_ARRAY_EQ_WITH_TOLERANCE(float, hm, dmt->data.f32, 10, 1e-6, "10d vector L2 normalize failure");
ccv_matrix_free(dmt);
}
TEST_CASE("summed area table without padding")
{
int i, j;
ccv_dense_matrix_t* dmt = ccv_dense_matrix_new(5, 4, CCV_8U | CCV_C3, 0, 0);
unsigned char* ptr = dmt->data.u8;
for (i = 0; i < dmt->rows; i++)
{
for (j = 0; j < dmt->cols; j++)
{
ptr[j * 3] = 1;
ptr[j * 3 + 1] = 2;
ptr[j * 3 + 2] = 3;
}
ptr += dmt->step;
}
ccv_dense_matrix_t* b = 0;
ccv_sat(dmt, &b, 0, CCV_NO_PADDING);
int sat[60] = { 1, 2, 3, 2, 4, 6, 3, 6, 9, 4, 8, 12,
2, 4, 6, 4, 8, 12, 6, 12, 18, 8, 16, 24,
3, 6, 9, 6, 12, 18, 9, 18, 27, 12, 24, 36,
4, 8, 12, 8, 16, 24, 12, 24, 36, 16, 32, 48,
5, 10, 15, 10, 20, 30, 15, 30, 45, 20, 40, 60 };
REQUIRE_ARRAY_EQ(int, sat, b->data.i32, 60, "4x5 matrix summed area table computation error");
ccv_matrix_free(dmt);
ccv_matrix_free(b);
}
TEST_CASE("summed area table with padding")
{
int i, j;
ccv_dense_matrix_t* dmt = ccv_dense_matrix_new(5, 3, CCV_8U | CCV_C3, 0, 0);
unsigned char* ptr = dmt->data.u8;
for (i = 0; i < dmt->rows; i++)
{
for (j = 0; j < dmt->cols; j++)
{
ptr[j * 3] = 1;
ptr[j * 3 + 1] = 2;
ptr[j * 3 + 2] = 3;
}
ptr += dmt->step;
}
ccv_dense_matrix_t* b = 0;
ccv_sat(dmt, &b, 0, CCV_PADDING_ZERO);
int sat[72] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 2, 3, 2, 4, 6, 3, 6, 9,
0, 0, 0, 2, 4, 6, 4, 8, 12, 6, 12, 18,
0, 0, 0, 3, 6, 9, 6, 12, 18, 9, 18, 27,
0, 0, 0, 4, 8, 12, 8, 16, 24, 12, 24, 36,
0, 0, 0, 5, 10, 15, 10, 20, 30, 15, 30, 45, };
REQUIRE_ARRAY_EQ(int, sat, b->data.i32, 72, "3x5 matrix summed area table (with padding) computation error");
ccv_matrix_free(dmt);
ccv_matrix_free(b);
}
#include "case_main.h"
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#define COMMAND_SIZE 70
#define CWD_SIZE 140
#define MAX_PARAMETERS 5
#define handsome TRUE
pid_t pid;
int main(int argc, char **argv)
{
printf("\n\nStartar shellJPH VERSION PERROR2.0\n\n");
printf("-------------ENJOY------------------\n\n");
char command_buf[COMMAND_SIZE]; /* Array att lägga in inmatningssträngen i */
char *first_token, *next_token; /* Tokens att spara delsträngar i */
char *arguments[MAX_PARAMETERS]; /* Array med parametrarna */
char *cwd; /* Pekare till "current working directory" */
char cwd_buf[CWD_SIZE]; /* Array att lägga i "current working directory" */
char *home; /* Pekare till hemkatalogen */
char *path; /* Används för cd:s argmument "path" */
int length; /* Variabel för längden på strängar */
int i; /* While-loop variabel */
int status; /* Returvärde (status) från barnprocesserna */
int return_value; /* Returvärde från funktioner ex: execvp */
int ochTeckenTal; /* Hjälpvariabel för hantering av bakgrundsprocesser */
int buf_counter; /* Hjälpvariabel Räknare */
cwd = getcwd(cwd_buf, CWD_SIZE); /* Sparar "current working directory" som getcwd (inbyggd funktion) returnerar */
printf("%s$ ", cwd); /* Skriver ut "current working directory" på terminalen */
struct timeval start, end; /* ------------------------------------------- */
int start_t, end_t; /* Variaber för att mäta processernas körtid */
double time_dif, start_time, end_time; /* ------------------------------------------- */
while(NULL != fgets(command_buf, COMMAND_SIZE, stdin)) /* Sparar inläst sträng (läses in med fgets (inbyggd funktion) från stdin (användarens input) */
{
buf_counter = 0; /* Initialiterar räknare och hjälpvariabler */
ochTeckenTal = 0;
while(1) /* Loopar igenom den inmatade bufferten */
{
if(command_buf[buf_counter] == '\n') /* Om vi i bufferten har "newline" tecken (vilket vi har då användarne trycker enter */
{
command_buf[buf_counter] = '\0'; /* Byter ut "newline" tecknet mot \0 för att kunna köra execvp (se längre ner) */
break;
}
buf_counter++;
}
first_token = strtok(command_buf, " "); /* Sparar första delsträngen i inmatningen som genereras av strtok (inbyggd funktion) */
if(first_token == NULL) /* Om delsträngen är NULL */
{
/* Gör vi ingenting */
}
else if(0 == strncmp(first_token, "exit", 4)) /* Kollar om "exit" finns i första delsträngen */
{
exit(0); /* Programmet avslutas normalt */
}
else if(0 == strncmp(first_token, "cd", 2)) /* Jämför första delsträngen med "cd" */
{
/* ------------------------ Hanterar _ _ cd _ _ och cd ----------------------- */
next_token = strtok(NULL, " "); /* Nästa delsträng */
if(next_token == NULL) /* Bara cd, inget mer */
{
home = getenv("HOME"); /* Hämta HOME variablen. */
chdir(home); /* Byt katalog till hemkatalogen */
}
/* ------------------------- Hanterar cd dir ----------------------------------*/
while(next_token != NULL) /* Så länge der finns fler arg. */
{
chdir(next_token); /* Byt katalog till det arg. */
next_token = strtok(NULL, " "); /* Hämta nästa arg */
}
}
/* ----- Här hanterar vi resten av alla världens kommandon (ex: ls -l, pwd, et.c) -------*/
else
{
next_token = strtok(NULL, " "); /* Hämtar (parsar) nästa delsträng */
arguments[0] = first_token; /* Tillderlar argumentarrayen sina bas delsträngar */
arguments[1] = next_token;
if(next_token != NULL) /* Så längde delsträngen inte är tom */
{
if(0 == strncmp(next_token, "&", 1)) /* Om nästa delsträng är "&" */
{
ochTeckenTal = 1; /* , 1-ställ hjälpvariabeln */
arguments[1] = NULL; /* och NULL-ställ första argumentet i arrayen.*/
}
/* Om de finns fler delsträngar att läsas in så gör det*/
i = 2;
while((arguments[i] = strtok(NULL, " ")) != NULL && i < MAX_PARAMETERS)
{
i++;
}
}
start_t = gettimeofday(&start, NULL); /* Klockar och sparar tiden i variabeln start */
pid = fork(); /* Skapar en ny process */
if(-1 == pid) /* Fork misslyckades */
{
perror("Fork misslyckades"); /* Skriv ut felmeddelande */
exit(1); /* Skicka statut onormalt avslut */
}
if(0 == pid) /* Barnet */
{
/* Här körs endast barnprocessens kod */
if(1 == ochTeckenTal) /* Kollar om det är en bakgrundsprocess */
{
printf("Gav upphov till en bakgrundsprocess pid: %d\n", getpid());
}
else
{
printf("Gav upphov till en förgrundsprocess pid %d\n", getpid());
}
return_value = execvp(arguments[0], arguments); /* Exekverar */
if (-1 == return_value) { /* Execvp misslyckades */
perror("Kunde inte köra execvp");
exit(1);
}
}
/*
*Om tecknet var 1-ställt tidigare så förekom det ett &-tecken, annars
*vänta på barnprocessen, klocka tiden och spara i slutvariabeln,
*skriva ut rätt värden på tiderna
*/
if(1 != ochTeckenTal)
{
wait(&status);
end_t = gettimeofday(&end, NULL);
unsigned int start_sec = start.tv_sec;
unsigned int start_usec = start.tv_usec;
unsigned int end_sec = end.tv_sec;
unsigned int end_usec = end.tv_usec;
if(start_t == 0 && end_t == 0)
{
start_time = start_sec + (start_usec/100000.0);
end_time = end_sec + (end_usec/100000.0);
time_dif = (end_time - start_time);
printf("Förgrundsprocess %d terminerade\nwallclock time: %.3f msec\n", pid, time_dif*1000);
}
}
/* Föräldern sover för snyggare utskrift */
usleep(10);
}
cwd = getcwd(cwd_buf, CWD_SIZE);
printf("%s$ ", cwd);
}
perror("fgets\n");
exit(1);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int asc(const void *a, const void *b)
{
return *(int *)a - *(int *)b;
}
int main()
{
int n, k;
scanf("%d %d", &n, &k);
int *p = (int *)malloc(sizeof(int) * n);
for (int i = 0; i < n; i++)
{
scanf("%d", &p[i]);
}
qsort(p, n, sizeof(int), asc);
int ans = 0;
for (int i = 0; i < k; i++)
{
ans += p[i];
}
printf("%d\n", ans);
free(p);
return 0;
}
|
C
|
#include<stdio.h>
int rev(int num){
int reminder,sum=0;
while(num!=0){
reminder=num%10;
sum=sum*10+reminder;
num=num/10;
}
return sum;
}
int main(){
int n;
scanf("%d",&n);
int reminder,sum=0;
int num=rev(n);
while(num!=0){
reminder=num%10;
if(reminder%2==0){
printf("%d is even",reminder);
}
else{
printf("%d is odd",reminder);
}
num=num/10;
printf("\n");
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* sh_process_shift_vertical.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ldedier <ldedier@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/06/03 22:47:48 by ldedier #+# #+# */
/* Updated: 2019/07/19 11:41:52 by ldedier ### ########.fr */
/* */
/* ************************************************************************** */
#include "sh_21.h"
int process_shift_up(t_command_line *command_line)
{
int cursor;
t_xy xy;
t_xy xy_iter;
cursor = g_glob.cursor;
xy = get_position(get_true_cursor_pos(g_glob.cursor));
while (command_line->current_index > 0)
{
command_line->current_index = get_left_w_char_index(command_line);
xy_iter = get_position(get_true_cursor_pos(--cursor));
if (xy_iter.x == xy.x && xy_iter.y == xy.y - 1)
{
render_command_line(command_line, cursor - g_glob.cursor, 1);
return (SUCCESS);
}
}
render_command_line(command_line, cursor - g_glob.cursor, 1);
return (SUCCESS);
}
int process_shift_down(t_command_line *command_line)
{
int cursor;
t_xy xy;
t_xy xy_iter;
cursor = g_glob.cursor;
xy = get_position(get_true_cursor_pos(g_glob.cursor));
while (command_line->current_index
< (int)command_line->dy_str->current_size)
{
command_line->current_index = get_right_w_char_index(command_line);
xy_iter = get_position(get_true_cursor_pos(++cursor));
if (xy_iter.x == xy.x && xy_iter.y == xy.y + 1)
{
render_command_line(command_line, cursor - g_glob.cursor, 1);
return (SUCCESS);
}
}
render_command_line(command_line, cursor - g_glob.cursor, 1);
return (SUCCESS);
}
|
C
|
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#define N 1000
#define FROM_MASTER 1
#define FROM_SLAVE 2
int A[N][N], B[N][N];
unsigned long long C[N][N];
MPI_Status status; //消息接收状态变量,存储也是分布的
int main(int argc, char **argv)
{
int p; //进程数,该变量为各处理器中的同名变量, 存储是分布的
int id;
int slave_num;
int dest; //目的进程标识号
int source; //发送数据进程的标识号
int rows;
int row_each;
int remainder;
int offset; //行偏移量
int i, j, k;
double start_time, end_time;
srand((unsigned int)time(NULL));
for(i=0; i<N; i++)
{
for(j=0; j<N; j++)
{
A[i][j] = rand() % 10;
B[i][j] = rand() % 10;
C[i][j] = 0;
}
}
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &id);
MPI_Comm_size(MPI_COMM_WORLD, &p);
if(p == 1)
{
fprintf(stderr,"the process number must bigger than 1\n");
MPI_Abort(MPI_COMM_WORLD, 1);
MPI_Finalize();
}
slave_num = p - 1;
if(id == 0)
{
row_each = N / slave_num;
remainder = N % slave_num;
offset = 0;
for(dest=1; dest<=slave_num; dest++)
{
rows = (dest <= remainder) ? row_each+1 : row_each;
printf("sending %d rows to process %d\n", rows, dest);
MPI_Send(&offset, 1, MPI_INT, dest, FROM_MASTER, MPI_COMM_WORLD);
MPI_Send(&rows, 1, MPI_INT, dest, FROM_MASTER, MPI_COMM_WORLD);
MPI_Send(&A[offset][0], rows*N, MPI_INT, dest, FROM_MASTER, MPI_COMM_WORLD);
MPI_Send(&B, N*N, MPI_INT, dest, FROM_MASTER, MPI_COMM_WORLD);
offset += rows;
}
start_time = MPI_Wtime();
for(source=1; source<=slave_num; source++)
{
MPI_Recv(&offset, 1, MPI_INT, source, FROM_SLAVE, MPI_COMM_WORLD, &status); //接收行偏移量
MPI_Recv(&rows, 1, MPI_INT, source, FROM_SLAVE, MPI_COMM_WORLD, &status); //接收行数
MPI_Recv(&C[offset][0], rows*N, MPI_UNSIGNED_LONG_LONG, source, FROM_SLAVE, MPI_COMM_WORLD, &status); //C接收从进程发回的结果
}
end_time = MPI_Wtime();
printf("process cost %f seconds\n", end_time-start_time);
}
if(id > 0)
{
MPI_Recv(&offset, 1, MPI_INT, 0, FROM_MASTER, MPI_COMM_WORLD, &status);
MPI_Recv(&rows, 1, MPI_INT, 0, FROM_MASTER, MPI_COMM_WORLD, &status);
MPI_Recv(&A, rows*N, MPI_INT, 0, FROM_MASTER, MPI_COMM_WORLD, &status);
MPI_Recv(&B, N*N, MPI_INT, 0, FROM_MASTER, MPI_COMM_WORLD, &status);
for(i=0; i<rows; i++)
{
for(k=0; k<N; k++)
{
int tmp = A[i][k];
for(j=0; j<N; j++)
{
C[i][j] += tmp*B[k][j];
}
}
}
MPI_Send(&offset, 1, MPI_INT, 0, FROM_SLAVE, MPI_COMM_WORLD); //将行偏移量发回主进程
MPI_Send(&rows, 1, MPI_INT, 0, FROM_SLAVE, MPI_COMM_WORLD); //将行数发回主进程
MPI_Send(&C, rows*N, MPI_UNSIGNED_LONG_LONG, 0, FROM_SLAVE, MPI_COMM_WORLD); //将计算得到的值发回主进程
}
MPI_Finalize();
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
int toupper(int c);
int counts(char sentence[], char letter, int size) {
int conta=0, i;
for(i=0;i<size;i++)
if(toupper(sentence[i]) == letter) conta++;
return conta;
}
int main() {
char sentence[256];
char letters[26] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int numbers[256], i, size;
printf("sentence: ");
fgets(sentence,256,stdin); //gets sentence
size = strlen(sentence);
for(int l=0; l<26; l++) // counts how many times each letter appears
numbers[l] = counts(sentence,letters[l],size);
for(i=0;i<26;i++) {
printf("%c ", letters[i]); //prints letter
for(int x=0;x<numbers[i];x++) //prints star x times (count)
printf("☆ ");
printf("\n");
}
return 0;
}
|
C
|
/*
============================================================================
Name : hev-task-channel.h
Author : Heiher <r@hev.cc>
Copyright : Copyright (c) 2019 everyone.
Description : Channel
============================================================================
*/
#ifndef __HEV_TASK_CHANNEL_H__
#define __HEV_TASK_CHANNEL_H__
#include <sys/types.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct _HevTaskChannel HevTaskChannel;
/**
* hev_task_channel_new:
* @chan1: (out): a #HevTaskChannel
* @chan2: (out): a #HevTaskChannel
*
* Creates a pair of connected task channel.
* The channels are synchronous, both sides of the channel will wait until the
* other side is ready.
*
* Returns: When successful, returns zero. When an error occurs, returns -1.
*
* Since: 4.5
*/
int hev_task_channel_new (HevTaskChannel **chan1, HevTaskChannel **chan2);
/**
* hev_task_channel_new_with_buffers:
* @chan1: (out): a #HevTaskChannel
* @chan2: (out): a #HevTaskChannel
* @size: buffer size
* @buffers: buffers capacity
*
* Creates a pair of connected task channel with a capacity of @buffers.
* The channels are asynchronous, sending or receiving a data will not wait
* unless the channel is already full.
*
* Returns: When successful, returns zero. When an error occurs, returns -1.
*
* Since: 5.1.0
*/
int hev_task_channel_new_with_buffers (HevTaskChannel **chan1,
HevTaskChannel **chan2,
unsigned int size, unsigned int buffers);
/**
* hev_task_channel_destroy:
* @self: a #HevTaskChannel
*
* Destroy the task channel.
*
* Since: 4.5
*/
void hev_task_channel_destroy (HevTaskChannel *self);
/**
* hev_task_channel_read:
* @self: a #HevTaskChannel
* @buffer: (array length=count): a buffer to read data into
* @count: the number of bytes that will be read
*
* The read function shall attempt to read @count bytes from the channel into
* @buffer. Just as datagram which the data transfer on task channel.
*
* Returns: the number of bytes actually read
*
* Since: 4.5
*/
ssize_t hev_task_channel_read (HevTaskChannel *self, void *buffer,
size_t count);
/**
* hev_task_channel_write:
* @self: a #HevTaskChannel
* @buffer: (array length=count): a buffer to write data from
* @count: the number of bytes that will be write
*
* The write function shall attempt to write @count bytes to the channel from
* @buffer. Just as datagram which the data transfer on task channel.
*
* Returns: the number of bytes actually write
*
* Since: 4.5
*/
ssize_t hev_task_channel_write (HevTaskChannel *self, const void *buffer,
size_t count);
#ifdef __cplusplus
}
#endif
#endif /* __HEV_TASK_CHANNEL_H__ */
|
C
|
#include <stdlib.h>
#include <unistd.h>
void ft_putchar(char c);
int is_positive(char *str);
int is_prime(unsigned int n);
void ft_putnbr(unsigned int n);
unsigned int to_int(char *str);
int main(int ac, char *av[])
{
unsigned int x;
unsigned int n;
unsigned int sum;
if (ac != 2)
{
ft_putchar('0');
ft_putchar('\n');
exit(0);
}
if (is_positive(av[1]) == 0)
{
ft_putchar('0');
ft_putchar('\n');
exit(0);
}
n = to_int(av[1]);
x = 0;
sum = 0;
while (x <= n)
{
if (is_prime(x) == 1)
sum += x;
x++;
}
ft_putnbr(sum);
ft_putchar('\n');
exit(0);
}
void ft_putchar(char c)
{
write(1, &c, 1);
}
int is_positive(char *str)
{
int i;
if (!str)
return (0);
i = 0;
if (str[i] == '0')
return (0);
while (str[i] != 0)
{
if (str[i] > '9' || str[i] < '0')
return (0);
i++;
}
return (1);
}
int is_prime(unsigned int n)
{
unsigned int x;
if (n == 0 || n == 1)
return (0);
if (n == 2)
return (1);
x = 2;
while (n % x != 0)
x++;
return (n == x ? 1 : 0);
}
void ft_putnbr(unsigned int n)
{
if (n >= 10)
ft_putnbr(n / 10);
ft_putchar(n % 10 + '0');
}
unsigned int to_int(char *str)
{
unsigned int sum;
int i = 0;
sum = 0;
while (str[i] != 0)
{
sum += str[i] - '0';
i++;
}
return (sum);
}
|
C
|
#include "input_val.h"
//Checks the input from the command line
void command_input_check(int argc) {
if(argc < 4) {
printf("Not enough arguments entered\n");
printf("Usage connectn.out num_rows num_columns number_of_pieces_in_a_row_needed_to_win\n");
exit(0);
}
else if (argc > 4) {
printf("Too many arguments entered\n");
printf("Usage connectn.out num_rows num_columns number_of_pieces_in_a_row_needed_to_win\n");
exit(0);
}
}
int game_mode(void) {
int mode, args;
do {
printf("Please choose the game mode.\n");
printf("1 - Vs. CPU.\n2 - Vs. Human.\n");
printf("Mode: ");
args = scanf("%d", &mode);
}
while(args != 1 || mode < 1 || mode > 2);
return mode;
}
int difficulty(void) {
int depth, args;
do {
printf("Please choose the level of difficulty.\n");
printf("1 (Easiest) - 10 (Hardest): ");
args = scanf("%d", &depth);
}
while(args != 1 || depth > 10 || depth < 1);
return depth;
}
//Checks if column is full
bool filled(char** board, int row, int col, int num_cols) {
int i;
bool filled = true;
if (row == 0 && num_cols == 2) {
return false;
}
//The column is not full if it has a *
for(i = 0; i < row; ++i) {
if(board[i][col] == '*') {
return false;
}
}
return filled;
}
bool consume_stdin(){
/*
Consume the remaining characters on the standard input
@returns: true if there are any non white space characters left
*/
char c;
int num_chars_read = 0;
bool leftovers = false;
do{
num_chars_read = scanf("%c", &c);
if(!isspace(c)){
leftovers = true;
}
}while(c != '\n' && num_chars_read > 0);
return leftovers;
}
bool min_valid_requirements(int num_args_read, int num_args_needed, bool nothing_else){
/*
the minimum requirements for input to be valid, which is that we were are actually able
to read something with scanf. If we fail to meet these requirements then the
remaining characters on the standard input are consumed to allow for new input.
@num_args_read: the number of arguments read by the last call to scanf
@num_args_needed: the number of arguments we wanted to read in the last scanf
@nothing_else: true if we wanted only exactly the elements in the last scanf to be read
false if you are ok with their being extra input afterwards
@returns: true if the last call to scanf successfully read all the elements
@modfies: stdin
*/
bool leftovers = false;
if(nothing_else || num_args_read != num_args_needed){
leftovers = consume_stdin();
}
return num_args_read == num_args_needed && !leftovers;
}
int get_int(char* prompt, bool nothing_else){
/*
get an integer from the user
@prompt: the prompt to be displayed to the user
@nothing_else: true if we wanted only exactly the elements in the last scanf to be read
false if you are ok with their being extra input afterwards
@returns: the first valid integer entered by the user
*/
int num;
int num_args_read;
do{
printf("%s", prompt);
num_args_read = scanf("%d", &num);
}while(!min_valid_requirements(num_args_read, 1, nothing_else));
return num;
}
int get_bound_int(char* prompt, bool nothing_else, int low, int high){
/*
get an integer from the user between low and high inclusive
@prompt: the prompt to be displayed to the user
@nothing_else: true if we wanted only exactly the elements in the last scanf to be read
false if you are ok with their being extra input afterwards
@low: the minimum allowable value for the integer
@high: the maximum allowable value for the integer
@returns: the first integer entered by the user between low and high
*/
int num;
do{
num = get_int(prompt, nothing_else);
}while(!(num >= low && num <= high));
return num;
}
void get_valid_move(char** board, int num_rows, int num_cols, int* row, int* col){
int num_args_read;
*row = num_rows - 1;
do{
printf("Enter a column between 0 and %d to play in: ", num_cols - 1);
num_args_read = scanf("%d", col);
}while(!is_valid_move(num_args_read, 1,
board, *row, *col,
num_rows, num_cols));
}
bool is_valid_move(int num_args_read, int num_args_needed, char** board, int row, int col, int num_rows, int num_cols){
bool leftovers = consume_stdin();
if(num_args_read != num_args_needed){
return false;
}
else if(leftovers){ //Checks for space after input
return false;
}
else if(!inbounds(row, col, num_rows, num_cols)){
return false;
}
else if(filled(board, row, col, num_cols)) {
return false;
}
else{
return true;
}
}
bool inbounds(int row, int col, int num_rows, int num_cols){
return row >= 0 && row < num_rows && col >= 0 && col < num_cols;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
/* spawning child processes using fork - forks off a process at a certain point */
/* Entire process gets forked from that process onwards while in pthread we name a func which will run as a context of a thread */
/* Fork uses the internal Clone api - pthread also uses it */
int main()
{
pid_t pid;
if( (pid = fork()) > 0) // parent process
{
printf("This is the parent process\n");
}
else // child process - =0
{
printf("This is printed from the context of child process\n");
}
}
|
C
|
#include <stdio.h>
int main(void) {
int arr[5] = { 1,2,3,4,5 };
int i;
for (i = 0; i < 5; i++) {
printf("%d ", &arr[i]);//迭 ü ּҰ
}
printf("\n");
return 0;
}
|
C
|
#include <lib.h>
#include <time.h>
#include <x86.h>
#include <errno.h>
#include <pit.h>
#include <kmm.h>
#define NTIMERS 128
static struct timer {
uint32_t start_ticks;
uint32_t stop_ticks;
bool active;
}* timers[NTIMERS];
static
struct time
msec2time(uint32_t msec) {
struct time t = {0};
t.msec = msec % 1000;
if ((msec /= 1000) != 0) {
t.sec = msec % 60;
if ((msec /= 60) != 0) {
t.min = msec % 60;
if ((msec /= 60) != 0)
t.hr = msec;
}
}
return t;
}
static
uint32_t
time2msec(struct time t) {
return ((t.hr * 60 + t.min) * 60 + t.sec) * 1000 + t.msec;
}
int
timer_create(void) {
for (int timer_id = 0; timer_id < NTIMERS; ++timer_id)
if (timers[timer_id] == NULL) {
timers[timer_id] = kmalloc(sizeof(struct timer));
return timer_id;
}
return ENTIMER;
}
void
timer_start(int timer_id) {
assert(timers[timer_id] != NULL);
assert(!timers[timer_id]->active);
timers[timer_id]->active = true;
timers[timer_id]->start_ticks = pit_ticks();
}
struct time
timer_lap(int timer_id) {
assert(timers[timer_id] != NULL);
assert(timers[timer_id]->active);
uint32_t now_ticks = pit_ticks();
uint32_t ticks = now_ticks - timers[timer_id]->start_ticks;
return msec2time(ticks);
}
struct time
timer_stop(int timer_id) {
assert(timers[timer_id] != NULL);
assert(timers[timer_id]->active);
timers[timer_id]->stop_ticks = pit_ticks();
timers[timer_id]->active = false;
uint32_t ticks = timers[timer_id]->stop_ticks - timers[timer_id]->start_ticks;
return msec2time(ticks);
}
void
timer_resume(int timer_id) {
assert(timers[timer_id] != NULL);
assert(!timers[timer_id]->active);
timers[timer_id]->active = true;
}
void
timer_reset(int timer_id) {
assert(timers[timer_id] != NULL);
timers[timer_id]->start_ticks = 0;
timers[timer_id]->stop_ticks = 0;
timers[timer_id]->active = false;
}
void
timer_delete(int timer_id) {
assert(timers[timer_id] != NULL);
assert(!timers[timer_id]->active);
kfree(timers[timer_id]);
timers[timer_id] = NULL;
}
void
print_time(struct time t) {
char buffer[32] = {0};
if (t.hr != 0)
snprintf(buffer, 32, "%u:%u:%u.%u", t.hr, t.min, t.sec, t.msec);
else if (t.min != 0)
snprintf(buffer, 32, "%u:%u.%u", t.min, t.sec, t.msec);
else
snprintf(buffer, 32, "%u.%u", t.sec, t.msec);
print("%s\n", buffer);
}
struct time
time_diff(struct time start, struct time stop) {
uint32_t ms_start = time2msec(start);
uint32_t ms_stop = time2msec(stop);
return ms_stop > ms_start ? msec2time(ms_stop - ms_start) : msec2time(ms_start - ms_stop);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.