language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char** argv){
if(argc!=2){ /****** Error checking *****/
printf("Error! I must get one argument!\n");
exit(-1);
}
FILE* f;
f=fopen(argv[1], "r");
if(f==NULL){ /****** Error checking *****/
printf("Error! Could not open file!\n");
exit(-2);
}
int pfd[2], pfd2[2];
if(pipe(pfd)==-1){ /****** Error checking *****/
printf("Error! Could not open pipe!\n");
exit(-3);
};
if(pipe(pfd2)==-1){ /****** Error checking *****/
printf("Error! Could not open pipe!\n");
exit(-3);
};
if(fork()==0){ // child
close(pfd[1]); // close write pipe;
close(pfd2[0]); // close read pipe;
//close(STDIN_FILENO);
dup2(pfd[0], STDIN_FILENO);
dup2(pfd2[1], STDOUT_FILENO);
execlp("sort", "sort", NULL);
printf("Error calling exec!\n");
exit(-10);
}
// Parent
close(pfd[0]); // close read pipe
close(pfd2[1]); // close write pipe
fseek(f, 0, SEEK_END);
long fsize=ftell(f);
//printf("Read %li bytes.\n", fsize);
char* buf=calloc(fsize+1, 1);
fseek(f, 0, SEEK_SET);
char c;
int i=0;
while((c=getc(f))!=EOF){
buf[i++]=c;
}
write(pfd[1], buf, fsize);
close(pfd[1]);
fclose(f);
read(pfd2[0], buf, fsize+1);
printf("%s", buf);
free(buf);
}
|
C
|
//1번째 시도
#include <stdio.h>
int main(void) {
int arr[1000] = { 0 };
int max = 0, min = 0, n;
scanf("%d", &n);
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
for (int i = 1; i <= n; i++) {
if (arr[i - 1] < arr[i]) max = arr[i];
if (arr[i - 1] > arr[i]) min = arr[i - 1];
}
printf("%d %d", min, max);
}
//런타임 에러
//2번째 시도
#include <stdio.h>
#include <stdlib.h>
int main() {
int max = 0, min = 0, n;
scanf("%d", &n);
int* arr = (int *)malloc(sizeof(int) * n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
if (arr[i] < max) max = arr[i];
if (arr[i] > min) min = arr[i];
}
printf("%d %d", min, max);
return 0;
}
//런타임 에러
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <curses.h>
#define DEFAULT 0
#define PREC 1
// HELP
#define ARGERR "USAGE:\n\
equ op n1 [n2 ... nX]\n\
n1: First parameter\n\
n2: Second parameter\n\
nX: Xth parameter\n\
op:\n"
#define ALLOPTS "OPTIONS:\n\
linear: f(x)= ax+b\n\
power: f(x)= a(b)^x\n\
exponent: quadratic+, highest degree a, first coefficient b\n"
#define LINUS "f(x)= ax+b\n\
USAGE:\n\
equ linear a b\n"
#define POWUS "f(x)= a(b)^x\n\
USAGE:\n\
equ power a b\n"
#define EXPUS "Quadratic and up; highest degree a, first coefficient b\n\
USAGE:\n\
equ exponent a b [c ... ]\n"
enum opType {
linear,
power,
exponent
};
enum set {
yes,
no
};
struct ops {
enum opType type;
unsigned short int highDeg;
double * op;
};
char * linearf(double x, double a, double b);
char * powerf(double x, double a, double b);
char * exponentf(double x, unsigned short int highDeg, double * vars);
char * autoRound(double number);
unsigned short int decimal(double number);
int main(int argc, char * argv[]) {
struct ops vars;
enum set funct;
double base = DEFAULT, xv;
short int count;
int ch;
char * ras;
if(argc < 3) {
fprintf(stderr, ARGERR);
fprintf(stderr, ALLOPTS);
}
else {
if(!strcmp("exponent", argv[1])) {
vars.highDeg = atof(argv[2]);
if(argc < (int) vars.highDeg + 4) {
fprintf(stderr, EXPUS);
}
else {
vars.type = exponent;
vars.op = (double *) malloc(sizeof(double) * ((int) vars.highDeg + 1));
for(count = 3; count <= argc - 1; count++) {
printf("%d..", (int) count);
vars.op[(int) count - 2] = atof(argv[(int) count]);
printf("OK\n");
}
printf("111\n");
funct = yes;
}
}
else {
fprintf(stderr, ALLOPTS);
funct = no;
}
if(funct == yes) {
printf("222\n");
xv = 0;
printf("333\n");
for(count = 0; count <= 5; count++) {
printf("444\n");
ras = exponentf(xv, vars.highDeg, vars.op);
printf("%s\n", ras);
printf("555\n");
free(ras);
printf("666\n");
xv += 1;
}
free(vars.op);
}
}
return 0;
}
char * exponentf(double x, unsigned short int highDeg, double * vars) {
printf("1\n");
char print[64], * ret, *xc, *y;
printf("2\n");
double b = 0;
printf("3\n");
short int count;
printf("4\n");
xc = autoRound(x);
printf("5\n");
for(count = (short int) highDeg; count >= 0; count--) {
printf(" %d\n", (int) highDeg - (int) count);
b += vars[(int) highDeg - (int) count] * pow(x, (int) count);
}
printf("6\n");
y = autoRound(b);
printf("7\n");
sprintf(print, "f(%s)= %s", xc, y);
printf("8\n");
ret = (char *) malloc(strlen(print) + 1);
printf("9\n");
strcpy(ret, print);
printf("10\n");
free(xc);
printf("11\n");
free(y);
printf("12\n");
return ret;
}
char * autoRound(double number) {
char * ret, print[32];
unsigned short int count, loc = decimal(number);
enum set found = false;
sprintf(print, "%lf", number);
for(count = loc + 6; count >= loc; count--) {
if(print[(int) count] != '0') {
if(print[(int) count] == '.') {
count -= 1;
}
ret = (char *) malloc((int) count + 2);
strncpy(ret, print, (int) count + 1);
ret[(int) count + 1] = '\0';
found = true;
break;
}
}
if(found == false) {
ret = (char *) malloc(strlen(print) + 1);
strcpy(ret, print);
}
return ret;
}
unsigned short int decimal(double number) {
char string[32];
unsigned short int count;
sprintf(string, "%lf", number);
for(count = 0; count <= strlen(string) - 1; count++) {
if(string[(int) count] == '.') {
break;
}
}
return count;
}
|
C
|
/* select 用法:
* int select(int nfds, fd_set *readfds, fd_set *writefd, fd_set *exceptfds, struct timeval *utimeout);
* readfds, writefds, exceptfds为所要监听的三个描述符集:
* ——readfds 监听文件描述符是否可读,不监听可以传入 NULL
* ——writefds 监听文件描述符是否可写 ,不监听可以传入 NULL
* ——exceptfds 监听文件描述符是否有异常,不监听可以传入 NULL
* nfds 是 select() 监听的三个描述符集中描述符的最大值+1
* timeout 设置超时时间
* 1. nfds必须被正确设置,一般取描述符集中描述符的最大值并加1。
* 2. 在非必须的情况下,尽量使用不超时的select(),即将utimeout参数设置为NULL。
* 3. timeout的值必须在每次select()之前重新赋值,因为操作系统会修改此值。
* while(1) {
* timeout.tv_sec = 1;
* timeout.tv_usec = 0;
* select(nfds, &readfds, &writefds, &exceptfds, &timeout);
* }
* 4. 由于select()会修改字符集,因此如果select()调用是在一个循环中,则描述符集必须被重新赋值。
*/
#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/file.h>
#include <unistd.h>
#include <getopt.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <time.h>
#include <string.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <errno.h>
#include <sys/sysinfo.h>
static int raw_fd = -1;
static int signal_pipe[2];
int cur_pos=0;
struct caped_info_t caped_info_list[MAX_DHCP_MSG]={0};
struct cap_config_t cap_config = {
/* Default options. */
interface: "eth0",
ifindex: 0,
arp: "\0\0\0\0\0\0", /* appease gcc-3.0 */
};
/* Signal handler */
static void signal_handler(int sig)
{
if (send(signal_pipe[1], &sig, sizeof(sig), MSG_DONTWAIT) < 0) {
LOG(LOG_ERR, "Could not send signal: %s",
strerror(errno));
}
}
int main(int argc, char *argv[])
{
unsigned char *message;
int len, sig, retval, max_fd;
fd_set rfds;
struct timeval tv;
struct dhcpMessage packet;
/* setup signal handlers */
socketpair(AF_UNIX, SOCK_STREAM, 0, signal_pipe);
signal(SIGUSR1, signal_handler);
if (read_interface("br0", &cap_config.ifindex,NULL, cap_config.arp) < 0){
LOG(LOG_ERR, "FATAL: couldn't read the interface.");
return 0;
}
for (;;) {
FD_ZERO(&rfds);
/* set raw_server */
if(raw_fd < 0){
if((raw_fd = raw_socket(cap_config.ifindex, SERVER_PORT)) < 0){
LOG(LOG_ERR, "FATAL: couldn't create raw server socket, %s", strerror(errno));
return 0;
}
}
if (raw_fd >= 0) FD_SET(raw_fd, &rfds);
FD_SET(signal_pipe[0], &rfds);
/* timeout interval 0.5s */
tv.tv_sec = 0;
tv.tv_usec = 500000;
/* select for non blocking */
max_fd = signal_pipe[0] > raw_fd ? signal_pipe[0] : raw_fd;
retval = select(max_fd + 1, &rfds, NULL, NULL, &tv);
if(retval <= 0){
DEBUG(LOG_ERR, "select no file for read or listening");
continue;
}
if(FD_ISSET(raw_fd, &rfds)){
if((len = get_raw_packet(&packet, raw_fd)) < 0)
continue;
if ((message = get_option(&packet, DHCP_MESSAGE_TYPE)) == NULL) {
DEBUG(LOG_ERR, "couldnt get option from packet -- ignoring");
continue;
}
if(*message == DHCPREQUEST){
/* dhcp data options format */
/* |ID|length| data | */
/* ^ */
/* get_option return *pos */
/* mac->data |hardeare type| macaddr| */
DEBUG(LOG_INFO, "get the DHCPREQUEST packet");
char *host_name = get_option(&packet, DHCP_HOST_NAME);
char *srcmac = get_option(&packet, DHCP_CLIENT_ID);
if(host_name && srcmac){
if(check_matched_mac(srcmac))
add_to_info_list(host_name, srcmac);
}
}
else{
DEBUG(LOG_INFO, "useless packet, keep listening");
continue;
}
}
if(FD_ISSET(signal_pipe[0], &rfds)){
if (read(signal_pipe[0], &sig, sizeof(sig)) < 0) {
DEBUG(LOG_ERR, "Could not read signal: %s", strerror(errno));
continue; /* probably just EINTR */
}
switch (sig) {
case SIGUSR1:
dump_caped_info_list(DUMP_FILE);
break;
}
}
}
return 0;
}
void dump_caped_info_list(char *dump_file)
{
int i=0;
FILE *fp;
char mac2s[18]={0};
if((fp=fopen(dump_file, "w")) == NULL){
DEBUG(LOG_ERR, "Open dump file(%s) failed",dump_file);
return;
}
else{
for(i=0;i<MAX_DHCP_MSG && caped_info_list[i].hostName !=NULL;i++){
memset(mac2s, 0, sizeof(mac2s));
sprintf(mac2s,"%02x:%02x:%02x:%02x:%02x:%02x\n",
caped_info_list[i].mac[0],caped_info_list[i].mac[1],caped_info_list[i].mac[2],
caped_info_list[i].mac[3],caped_info_list[i].mac[4],caped_info_list[i].mac[5]);
fwrite(caped_info_list[i].hostName, strlen(caped_info_list[i].hostName), 1,fp);
fwrite(",", 1, 1,fp);
fwrite(mac2s, sizeof(mac2s), 1,fp);
}
fclose(fp);
}
return;
}
int check_matched_mac(u_int8_t *mac)
{
int i=0, j, count;
while(caped_info_list[i].hostName != NULL && i < MAX_DHCP_MSG){
count = 0;
for(j=0;j < 6; j++){
if(caped_info_list[i].mac[j] == mac[j+1]){
count++;
}
}
if(count == 6){
DEBUG(LOG_INFO, "The mac(%02x:%02x:%02x:%02x:%02x:%02x) had already record", mac[1],mac[2],mac[3],mac[4],mac[5],mac[6]);
return 0;
}
i++;
}
DEBUG(LOG_INFO, "The mac(%02x:%02x:%02x:%02x:%02x:%02x) is a new device", mac[1],mac[2],mac[3],mac[4],mac[5],mac[6]);
return 1;
}
void add_to_info_list(char *name, u_int8_t *mac)
{
int i;
if(caped_info_list[cur_pos].hostName != NULL){
free(caped_info_list[cur_pos].hostName);
}
caped_info_list[cur_pos].hostName = (char*)malloc(sizeof(char)*name[-1] +1);
strncpy(caped_info_list[cur_pos].hostName, name, name[-1]);
caped_info_list[cur_pos].hostName[name[-1]] = '\0';
for(i=0; i<6;i++)
caped_info_list[cur_pos].mac[i]=mac[i+1];
cur_pos = (cur_pos +1)%MAX_DHCP_MSG;
return;
}
/* return -1 on errors that are fatal for the socket, -2 for those that aren't */
int get_raw_packet(struct dhcpMessage *payload, int fd)
{
int bytes;
struct udp_dhcp_packet packet;
u_int32_t source, dest;
u_int16_t check;
memset(&packet, 0, sizeof(struct udp_dhcp_packet));
bytes = read(fd, &packet, sizeof(struct udp_dhcp_packet));
if (bytes < 0) {
DEBUG(LOG_INFO, "couldn't read on raw listening socket -- ignoring");
usleep(500000); /* possible down interface, looping condition */
return -1;
}
if (bytes < (int) (sizeof(struct iphdr) + sizeof(struct udphdr))) {
DEBUG(LOG_INFO, "message too short, ignoring");
return -2;
}
if (bytes < ntohs(packet.ip.tot_len)) {
DEBUG(LOG_INFO, "Truncated packet");
return -2;
}
/* ignore any extra garbage bytes */
bytes = ntohs(packet.ip.tot_len);
#if 0
/* Make sure its the right packet for us, and that it passes sanity checks */
if (packet.ip.protocol != IPPROTO_UDP || packet.ip.version != IPVERSION ||
packet.ip.ihl != sizeof(packet.ip) >> 2 || packet.udp.dest != htons(CLIENT_PORT) ||
bytes > (int) sizeof(struct udp_dhcp_packet) ||
ntohs(packet.udp.len) != (short) (bytes - sizeof(packet.ip))) {
DEBUG(LOG_INFO, "unrelated/bogus packet");
return -2;
}
#endif
/* check IP checksum */
check = packet.ip.check;
packet.ip.check = 0;
if (check != checksum(&(packet.ip), sizeof(packet.ip))) {
DEBUG(LOG_INFO, "bad IP header checksum, ignoring");
return -1;
}
/* verify the UDP checksum by replacing the header with a psuedo header */
source = packet.ip.saddr;
dest = packet.ip.daddr;
check = packet.udp.check;
packet.udp.check = 0;
memset(&packet.ip, 0, sizeof(packet.ip));
packet.ip.protocol = IPPROTO_UDP;
packet.ip.saddr = source;
packet.ip.daddr = dest;
packet.ip.tot_len = packet.udp.len; /* cheat on the psuedo-header */
if (check && check != checksum(&packet, bytes)) {
DEBUG(LOG_ERR, "packet with bad UDP checksum received, ignoring");
return -2;
}
memcpy(payload, &(packet.data), bytes - (sizeof(packet.ip) + sizeof(packet.udp)));
if (ntohl(payload->cookie) != DHCP_MAGIC) {
LOG(LOG_ERR, "received bogus message (bad magic) -- ignoring");
return -2;
}
DEBUG(LOG_INFO, "oooooh!!! got some!");
return bytes - (sizeof(packet.ip) + sizeof(packet.udp));
}
|
C
|
#include<stdio.h>
int main(){
int n;
scanf("%d",&n);
int arr[n], i = 0;
for(;i<n;i++) scanf("%d", &arr[i]);
//logic to get index of last found
//1 2 3 1 4 1
int key;
scanf("%d", &key);
int lastIndex = -1;
for(i = 0; i < n; i++){
if(arr[i] == key){
lastIndex = i;
}
}
if(lastIndex != -1){
printf("\n Last Found at index %d", lastIndex);
}
else {
printf("Not found");
}
}
|
C
|
#include<stdio.h>
int valor(int n1, int n2){
if (n1>n2) printf("Os valores em ordem crescente sao : %d %d",n2,n1);
else printf("Os valores em ordem crescente sao: %d %d",n1,n2);
}
int main(){
int num1,num2;
printf("Digite os valores ");
scanf("%d %d",&num1,&num2);
valor(num1,num2);
}
|
C
|
/* Student Name: Mishaal Fadhl
* Student Number: 991454815
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CLASS_SIZE 30
typedef struct student{
char *name; /* student name */
char *number; /* student number */
struct student *left; /* pointer to left subtree */
struct student *right; /* pointer to right subtree */
}Student;
Student* make_node (char*, char*);
void print_array(Student**, int);
void sort_array (Student**, int);
void print_inorder (Student*);
Student* make_tree (Student *, Student**, int, int);
Student* delete_node (Student*, char*);
/* 1215_42314 */
|
C
|
#include "yp_list.h"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
static void print_node_pointer(yp_list_node* node) {
if (node == NULL) {
return;
}
if (node->next == NULL) {
printf("%p", node);
} else {
printf("%p->", node);
}
}
yp_list* list_create() {
yp_list* list = (yp_list*)malloc(sizeof(yp_list));
if (!list) {
return NULL;
}
list->head = list->tail = NULL;
list->len = 0;
list->copy_value = NULL;
list->free_value = NULL;
list->compare_value = NULL;
list->visit = print_node_pointer;
return list;
}
yp_list* list_push(yp_list* list, void* p) {
yp_list_node* node = NULL;
if (list == NULL) {
return list;
}
node = (yp_list_node*)malloc(sizeof(yp_list_node));
if (!node) {
return NULL;
}
node->value = p;
node->next = NULL;
if (list->head == NULL) {
list->head = list->tail = node;
} else {
list->tail->next = node;
list->tail = node;
}
list->len++;
return list;
}
void* list_pop(yp_list* list) {
void* p = NULL;
yp_list_node* node = NULL, *q = NULL;
if (list == NULL || list->tail == NULL) {
return NULL;
}
q = list->tail;
if (list->head == list->tail) {
list->head = list->tail = NULL;
} else {
node = list->head;
while (node->next != list->tail) {
node = node->next;
}
list->tail = node;
node->next = NULL;
}
list->len--;
p = q->value;
free(q);
q = NULL;
return p;
}
void* list_shift(yp_list* list) {
yp_list_node* p = NULL;
void* value = NULL;
if (list == NULL || list->head == NULL) {
return NULL;
}
p = list->head;
if (list->head == list->tail) {
list->head = list->tail = NULL;
} else {
list->head = list->head->next;
}
value = p->value;
list->len--;
free(p);
p = NULL;
return value;
}
yp_list* list_unshift(yp_list* list, void* p) {
yp_list_node* node = NULL;
if (list == NULL || p == NULL) {
return NULL;
}
node = (yp_list_node*)malloc(sizeof(yp_list_node));
if (!node) {
return NULL;
}
node->value = p;
node->next = NULL;
if (list->head == NULL) {
list->head = list->tail = node;
} else {
node->next = list->head;
list->head = node;
}
list->len++;
return list;
}
yp_list_node* list_ith_node(yp_list* list, int i) {
yp_list_node* p = NULL;
int count = 1;
if (list == NULL || i < 1 || i > list->len) {
return NULL;
}
p = list->head;
while (p && count < i) {
p = p->next;
count++;
}
return p;
}
void* list_get_last(yp_list* list) {
yp_list_node* node = NULL;
node = list_ith_node(list, list->len);
return node->value;
}
static yp_list_node* _list_reverse_r(yp_list_node* head) {
yp_list_node* p = NULL, *q = NULL;
if (head == NULL || head->next == NULL) {
return head;
}
p = head->next;
q = _list_reverse_r(p);
p->next = head;
head->next = NULL;
return q;
}
yp_list* list_reverse_r(yp_list* list) {
yp_list_node* p = NULL;
if (list == NULL) {
return NULL;
}
p = _list_reverse_r(list->head);
list->tail = list->head;
list->head = p;
return list;
}
yp_list* list_reverse(yp_list* list) {
yp_list_node* pre = NULL, *cur = NULL, *post = NULL, *tmp = NULL;
if (list == NULL || list->head == NULL) {
return list;
}
cur = list->head;
while (cur) {
post = cur->next;
cur->next = pre;
pre = cur;
cur = post;
}
tmp = list->head;
list->head = list->tail;
list->tail = tmp;
return list;
}
yp_list* list_empty(yp_list* list) {
yp_list_node* p = NULL, *q = NULL;
if (list == NULL || list->head == NULL) {
return NULL;
}
p = list->head;
while(p) {
q = p;
p = p->next;
free(q);
q = NULL;
}
list->head = list->tail = NULL;
list->len = 0;
return list;
}
void list_destroy(yp_list* list) {
list_empty(list);
free(list);
list = NULL;
}
void list_traverse(yp_list* list) {
yp_list_node* node = NULL;
int count = 0;
if (list == NULL) {
return;
}
node = list->head;
//使用count使得可以遍历存在环的情况
while (node && count++ <= list->len) {
if (list->visit) {
list->visit(node);
}
node = node->next;
}
}
|
C
|
// dracula.c
// Implementation of your "Fury of Dracula" Dracula AI
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "Game.h"
#include "DracView.h"
#include "Map.h"
#define TOTAL_AMBIGUOUS_MOVES 7
static void checkAmbiguousMovesAvailability(int *ambiguousMoves, Round currRound);
static void validateDoubleBackandHide(DracView gameState, int *ambiguousMoves, LocationID currPos);
static char *ambiguousIdToAbbrev(LocationID move);
static void incrementNumOfLocations(int *ambiguousMoves, int *numAmbiguousMoves);
static LocationID *createPossibleMovesArray(LocationID *legalMoves, int numLocations, int numAmbiguousMoves,
int *totalNumMoves, int *ambiguousMoves);
void decideDraculaMove(DracView gameState)
{
Round currRound = giveMeTheRound(gameState);
LocationID currPos = whereIs(gameState, PLAYER_DRACULA);
int numLocations = 0; int numAmbiguousMoves = 0; int totalNumMoves = 0;
srand(time(NULL)); // set a seed
char *nextMove;
printf("\n");
printf("currRound: %d\n", currRound);
printf("dracPos: %d\n", currPos);
if (currRound == 0) {
// when starting out, we place Dracula in MUNICH
registerBestPlay("MU", "Mwuhahahaha");
} else {
// we want to consider all possible Moves
// on LAND and WATER for dracula
LocationID dracTrail[TRAIL_SIZE]; giveMeTheTrail(gameState, PLAYER_DRACULA, dracTrail);
LocationID dracTrailMoves[TRAIL_SIZE]; giveMeTheMoves(gameState, PLAYER_DRACULA, dracTrailMoves);
LocationID *legalMoves = whereCanIgo(gameState, &numLocations, TRUE, TRUE);
Map g = newMap(); int numLocs = 0;
LocationID *adjacentLocations = reachableLocations(g, &numLocs, currPos, TRUE, FALSE, TRUE, TRUE);
// used for debugging purposes
//----------------------------------------
printf("adjacentLocations: ");
int j;
for (j = 0; j < numLocs; j++) {
printf("[%d]", adjacentLocations[j]);
}
printf("\n");
//----------------------------------------
printf("dracTrail: ");
for (j = 0; j < TRAIL_SIZE; j++) {
printf("[%d]", dracTrail[j]);
}
printf("\n");
//----------------------------------------
printf("dracTrailMoves: ");
for (j = 0; j < TRAIL_SIZE; j++) {
printf("[%d]", dracTrailMoves[j]);
}
printf("\n");
//----------------------------------------
printf("legalMoves: ");
for (j = 0; j < numLocations; j++) {
printf("[%d][%s] ", legalMoves[j], idToAbbrev(legalMoves[j]));
}
printf("\n");
//----------------------------------------
// | [0] = db1 | [1] = db2 | [2] = db3 | [3] = db4 | [4] = db5 | [5] = h1 | [6] = tp |
int ambiguousMoves[TOTAL_AMBIGUOUS_MOVES];
int i = 0; for (i = 0; i < TOTAL_AMBIGUOUS_MOVES; i++) { ambiguousMoves[i] = FALSE; }
checkAmbiguousMovesAvailability(ambiguousMoves, currRound);
validateDoubleBackandHide(gameState, ambiguousMoves, currPos);
incrementNumOfLocations(ambiguousMoves, &numAmbiguousMoves);
LocationID *possibleMoves = createPossibleMovesArray(legalMoves, numLocations, numAmbiguousMoves, &totalNumMoves, ambiguousMoves);
// used for debugging
printf("ambiguousMoves: ");
for (i = 0; i < TOTAL_AMBIGUOUS_MOVES; i++) {
printf("[%d] ", ambiguousMoves[i]);
}
printf("\n");
printf("numLocations: %d\n", numLocations);
printf("numAmbiguousMoves: %d\n", numAmbiguousMoves);
printf("totalNumMoves: %d\n", totalNumMoves);
printf("possibleMoves: ");
for (i = 0; i < totalNumMoves; i++) {
printf("[%d] ", possibleMoves[i]);
}
printf("\n");
LocationID chosenMove; int chosenIndex = 0;
chosenIndex = rand() % totalNumMoves;
chosenMove = possibleMoves[chosenIndex];
if (!validPlace(chosenMove)) {
nextMove = ambiguousIdToAbbrev(chosenMove);
} else {
nextMove = idToAbbrev(chosenMove);
}
// freeing the malloc'd pointers
free(legalMoves); legalMoves = NULL;
free(possibleMoves); possibleMoves = NULL;
free(legalMoves); legalMoves = NULL;
free(adjacentLocations); adjacentLocations = NULL;
disposeMap(g);
printf("nextMove: [%s]", nextMove);
// IF THIS WORKS, Dracula should be able to randomly choose and make any possible legal move
registerBestPlay(nextMove, "Mwuhahahaha");
}
}
//--------------------------- Auxillary functions ---------------------------
static void checkAmbiguousMovesAvailability(int *ambiguousMoves, Round currRound)
{
if (currRound >= 1) { ambiguousMoves[0] = TRUE; ambiguousMoves[5] = TRUE; }
if (currRound >= 2) { ambiguousMoves[1] = TRUE; }
if (currRound >= 3) { ambiguousMoves[2] = TRUE; }
if (currRound >= 4) { ambiguousMoves[3] = TRUE; }
if (currRound >= 5) { ambiguousMoves[4] = TRUE; }
}
static void validateDoubleBackandHide(DracView gameState, int *ambiguousMoves, LocationID currPos)
{
Map g = newMap(); int numLocs = 0;
LocationID *adjacentLocations = reachableLocations(g, &numLocs, currPos, TRUE, FALSE, TRUE, TRUE);
LocationID dracTrail[TRAIL_SIZE]; giveMeTheTrail(gameState, PLAYER_DRACULA, dracTrail);
int canDB = TRUE;
LocationID dracMovesTrail[TRAIL_SIZE]; giveMeTheMoves(gameState, PLAYER_DRACULA, dracMovesTrail);
int i; int move;
// apparently the last value in the trail is not counted as a move...
for (i = 0; i < TRAIL_SIZE-1; i++) {
move = dracMovesTrail[i];
switch (move) {
case DOUBLE_BACK_1: ambiguousMoves[0] = FALSE; canDB = FALSE; break;
case DOUBLE_BACK_2: ambiguousMoves[1] = FALSE; canDB = FALSE; break;
case DOUBLE_BACK_3: ambiguousMoves[2] = FALSE; canDB = FALSE; break;
case DOUBLE_BACK_4: ambiguousMoves[3] = FALSE; canDB = FALSE; break;
case DOUBLE_BACK_5: ambiguousMoves[4] = FALSE; canDB = FALSE; break;
case HIDE: ambiguousMoves[5] = FALSE; break;
}
}
// we can't double back to a location that is NOT adjacent to where we are
int ambiguousCounter; int adjCounter; LocationID adjLoc;
for (ambiguousCounter = 1; ambiguousCounter < 5; ambiguousCounter++) {
if (ambiguousMoves[ambiguousCounter] == TRUE) {
for (adjCounter = 0; adjCounter < numLocs; adjCounter++) {
adjLoc = adjacentLocations[adjCounter];
if (dracTrail[ambiguousCounter] != adjLoc) { ambiguousMoves[ambiguousCounter] = FALSE; }
else if (dracTrail[ambiguousCounter] == adjLoc) { ambiguousMoves[ambiguousCounter] = TRUE; break; }
}
}
}
// if one double back move is in the trail,
// then all double backs move 1 to 5 are canceled
if (canDB == FALSE) {
for (i = 0; i < 5; i++) {
ambiguousMoves[i] = FALSE;
}
}
// Drac cannot hide at Sea
if (isSea(dracTrail[0])) { ambiguousMoves[5] = FALSE; }
disposeMap(g); free(adjacentLocations); adjacentLocations = NULL;
}
static char *ambiguousIdToAbbrev(LocationID move)
{
char *nextMove = NULL;
switch (move) {
case DOUBLE_BACK_1: nextMove = "D1"; break;
case DOUBLE_BACK_2: nextMove = "D2"; break;
case DOUBLE_BACK_3: nextMove = "D3"; break;
case DOUBLE_BACK_4: nextMove = "D4"; break;
case DOUBLE_BACK_5: nextMove = "D5"; break;
case HIDE: nextMove = "HI"; break;
case TELEPORT: nextMove = "TP"; break;
}
return nextMove;
}
static void incrementNumOfLocations(int *ambiguousMoves, int *numAmbiguousMoves)
{
// NOTE: the * operator takes precedence over the ++ operator, and the () operators take precedence over everything else.
if (ambiguousMoves[0] == TRUE) { (*numAmbiguousMoves)++; }
if (ambiguousMoves[1] == TRUE) { (*numAmbiguousMoves)++; }
if (ambiguousMoves[2] == TRUE) { (*numAmbiguousMoves)++; }
if (ambiguousMoves[3] == TRUE) { (*numAmbiguousMoves)++; }
if (ambiguousMoves[4] == TRUE) { (*numAmbiguousMoves)++; }
if (ambiguousMoves[5] == TRUE) { (*numAmbiguousMoves)++; }
if (ambiguousMoves[6] == TRUE) { (*numAmbiguousMoves)++; }
}
static LocationID *createPossibleMovesArray(LocationID *legalMoves, int numLocations, int numAmbiguousMoves,
int *totalNumMoves, int *ambiguousMoves)
{
*totalNumMoves = numLocations + numAmbiguousMoves;
if (*totalNumMoves == 0) {
*totalNumMoves = 1;
LocationID *possibleMoves = malloc(sizeof(LocationID) * (*totalNumMoves));
possibleMoves[0] = TELEPORT;
return possibleMoves;
}
LocationID *possibleMoves = malloc(sizeof(LocationID) * (*totalNumMoves));
int i = 0; int ambiguousMovesCounter = 0;
for (i = 0; i < numLocations; i++) {
LocationID legalMove = legalMoves[i];
possibleMoves[i] = legalMove;
}
for (i = numLocations; i < *totalNumMoves+1; i++) {
while (ambiguousMoves[ambiguousMovesCounter] != TRUE && ambiguousMovesCounter < TOTAL_AMBIGUOUS_MOVES) {
ambiguousMovesCounter++;
}
if (ambiguousMoves[ambiguousMovesCounter] == TRUE) {
switch (ambiguousMovesCounter) {
case 0: possibleMoves[i] = DOUBLE_BACK_1; break;
case 1: possibleMoves[i] = DOUBLE_BACK_2; break;
case 2: possibleMoves[i] = DOUBLE_BACK_3; break;
case 3: possibleMoves[i] = DOUBLE_BACK_4; break;
case 4: possibleMoves[i] = DOUBLE_BACK_5; break;
case 5: possibleMoves[i] = HIDE; break;
}
ambiguousMovesCounter++;
}
}
return possibleMoves;
}
|
C
|
#include <intrinsics.h>
#include "io430.h"
#include "softuart.h"
// the following number allows you to introduce a predictable error rate
// If the value of ERROR_LEVEL is 100 then one bit in every 100 should be wrong
#define ERROR_LEVEL 2003
#define TX_PIN_HIGH (P1OUT |= 2)
#define TX_PIN_LOW (P1OUT &= 0xfd)
// Not using parity checking in this simple software UART.
byte TXBuffer;
typedef struct tagUARTStatus {
byte Busy : 1;
byte BitCounter : 4;
} UARTStatus;
volatile UARTStatus TXStatus;
volatile unsigned int milliseconds=0;
unsigned int ticks=0;
unsigned int ErrorCounter=ERROR_LEVEL;
#pragma vector=TIMERA0_VECTOR
__interrupt void OnTimer(void)
{
poll_UART();
ticks++;
if (ticks > 2) {
milliseconds++; // approx 1 ms timebase.
ticks=0;
}
if (milliseconds > 1000)
{
milliseconds = 0;
}
}
void initUART() {
TX_PIN_HIGH;
P1DIR |= 2;
TXStatus.Busy = TXStatus.BitCounter = 0;
TXBuffer = 0;
// set up Timer A to manage the transmission of bits.
TACTL = MC_1+TASSEL_2+TACLR;
TACCR0=417;// 1000000 / 2400 = 417 approx (needs tweaking in practice)
TACCTL0 = CCIE;
milliseconds = 0;
__enable_interrupt();
}
void putc(char c) {
int i;
TXBuffer = c;
TX_PIN_HIGH;
TXStatus.BitCounter = 10; // 1 start bit, 8 data bits and 1 stop bit
TACTL |= TACLR;
TXStatus.Busy = 1;// This actually starts the transmission
P1OUT |=BIT6; // show UART state
while (TXStatus.Busy) {
}
TX_PIN_HIGH;
delay(2);
P1OUT &=~BIT6; // show UART state
}
void poll_UART()
{
if (TXStatus.Busy) {
if (TXStatus.BitCounter==10) {
// sending start bit
TXStatus.BitCounter--;
TX_PIN_LOW;
}
else if (TXStatus.BitCounter > 1) {
TXStatus.BitCounter--;
ErrorCounter--;
if (ErrorCounter) {
if ((TXBuffer & 1))
TX_PIN_HIGH;
else
TX_PIN_LOW;
}
else {
// deliberately send the wrong bit
if ((TXBuffer & 1))
TX_PIN_LOW;
else
TX_PIN_HIGH;
ErrorCounter = ERROR_LEVEL;
}
TXBuffer = TXBuffer >> 1;
} else {
// send the stop bit
TXStatus.BitCounter--;
TX_PIN_HIGH;
TXStatus.Busy = 0;
}
}
}
void TXString(char * s) {
while(*s) {
putc(*s++);
delay(2);
}
}
void TXDecimal(int Number) {
char c;
c = ( Number / 10000)+48;
putc(c);
Number = Number % 10000;
c = ( (Number / 1000))+48;
putc(c);
Number = Number % 1000;
c = ( (Number / 100))+48;
putc(c);
Number = Number % 100;
c = ( (Number / 10 ))+48;
putc(c);
Number = Number % 10;
c = ( (Number ))+48;
putc(c);
}
void TXHex(int Number) {
char c;
c = (Number >> 12) & 0x0f;
if (c > 9)
c = c+55;
else
c = c+48;
putc(c);
c = (Number >> 8) & 0x0f;
if (c > 9)
c = c+55;
else
c = c+48;
putc(c);
c = (Number >>4) & 0x0f;
if (c > 9)
c = c+55;
else
c = c+48;
putc(c);
c = (Number) & 0x0f;
if (c > 9)
c = c+55;
else
c = c+48;
putc(c);
}
void delay(int millis) {
/* int i;
while (millis--)
for(i=0;i<100;i++);*/
milliseconds = 0;
while (milliseconds < millis);
}
|
C
|
/*
* mempool:
* Variable-size memory allocator without support for individual deallocation.
*/
#ifndef MEMPOOL_H
#define MEMPOOL_H
#include <stdlib.h>
struct mempool_block
{
struct mempool_block *prev; /* previous block in the chain */
size_t alloc_size; /* allocated size */
size_t size; /* usable size */
};
struct mempool_chain
{
struct mempool_block *last; /* last block */
size_t last_free; /* free memory in last block */
size_t total_size; /* total size of the chain */
size_t num_blocks; /* number of blocks in the chain */
};
struct mempool
{
struct mempool_chain small; /* chain of blocks for small objects */
struct mempool_chain big; /* chain of blocks for big objects */
struct mempool_chain unused; /* chain of unused blocks */
size_t block_size; /* size of small objects block */
size_t small_treshold; /* maximum size of a small object */
};
void mempool_init(struct mempool *pool, size_t block_size);
void mempool_free(struct mempool *pool);
void *mempool_alloc(struct mempool *pool, size_t size);
char *mempool_memcpy(struct mempool *pool, char *src, size_t len);
char *mempool_strdup(struct mempool *pool, char *str);
void mempool_print_stats(struct mempool *pool);
#endif
|
C
|
//
// MCSampler1D.h
// VolumeSingleScatter
//
// Created by WangYue on 2016-11-30.
// Copyright © 2016 WangYue. All rights reserved.
//
#ifndef MCSampler1D_h
#define MCSampler1D_h
enum sampleMode1D{
Distance,
EquiAngular
};
double EquiAngularSampling(Ray& ray, Vector3& lightPos, double t_MAX,double sigmaT, double& pdf,double& temp ){
double t_sample;
// PDF: p(t) = D / ((theta_b − theta_a)(D2 +t2));
// t(x) = D * tan(1− randf()) * theta_a + randf() * theta_b;
// theta_x = atan(x/D);
Vector3 rayOrigin = ray.getOrigin();
Vector3 rayDir = ray.getDirection();
// get coord of closest point to light along (infinite) ray
double delta = (lightPos - rayOrigin).dot(rayDir);
// get distance this point is from light
double D = (rayOrigin + rayDir * delta - lightPos).length();
// get angle of endpoints
double thetaA = - atan(delta / D);
double thetaB = atan((t_MAX - delta) / D);
// take sample
double u = randf();
double t = D * tan(thetaA *(1 - u)+ thetaB * u);
// // debug
temp = (D*D + t*t);
t_sample = delta + t;
pdf = D/((thetaB - thetaA)*(D*D + t*t));
return t_sample;
};
double distanceSampling(double t_MAX,double sigmaT, double& pdf){
double t_sample;
// PDF: p(t) = (sigmaT / (1 - exp(sigmaT * t_MAX))) * exp(-sigmaT * t);
// CDF: P(t) = (1 - exp(-sigmaT * t))/(1 - exp(-sigmaT * t_MAX));
// INVERSE: t = - ln(1 - randf() * (1 - exp(sigmaT * t_MAX))) / sigmaT;
t_sample = - log(1 - randf() * (1 - exp(- sigmaT * t_MAX))) / sigmaT;
pdf = sigmaT * exp( - sigmaT * t_sample) / (1 - exp( - sigmaT * t_MAX));
return t_sample;
};
//double sample1D(Ray& ray, Vector3& lightPos, double t_MAX,double sigmaT, double& pdf,sampleMode1D sampleMode){
// double t_sample;
//
// switch (sampleMode) {
// case EquiAngular:
// t_sample = EquiAngularSampling(ray, lightPos, t_MAX, sigmaT, pdf);
// break;
//
// default:
// t_sample = distanceSampling(t_MAX, sigmaT, pdf);
// }
//
//
//
// return t_sample;
//
//};
double sample1DDBG(Ray& ray, Vector3& lightPos, double t_MAX,double sigmaT, double& pdf,sampleMode1D sampleMode, double& temp){
double t_sample;
switch (sampleMode) {
case EquiAngular:
t_sample = EquiAngularSampling(ray, lightPos, t_MAX, sigmaT, pdf, temp);
break;
default:
t_sample = distanceSampling(t_MAX, sigmaT, pdf);
}
return t_sample;
};
#endif /* MCSampler1D_h */
|
C
|
//implementing stack using linked list
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node*link;
};
struct node* top;
void push(int x)
{
struct node*temp=malloc(sizeof(struct node));
temp->data=x;
temp->link=top;
top=temp;
}
void pop()
{
struct node*temp;
if(top==NULL)
{
printf("stack is empty");
return;
}
temp=top;
top=top->link;
free(temp);
}
void display()
{
struct node*temp=top;
while(temp != NULL)
{
printf("%d ",temp->data);
temp=temp->link;
}
printf("\n");
}
int IsEmpty()//return 0 if not empty and 1 if empty
{
return top == NULL;
}
// function to return top element in a stack
int Top()
{
if (!IsEmpty())
return top->data;
else
exit(0);
}
int main()
{
int choice,value;
while(1)
{
printf("\n******MENNNNUUUU*****\n");
printf("\n1.push\n2.pop\n3.display\n4.exit\n5.IsEmpty\n6.Top\n");
printf("enter your choice:: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
printf("enter the value to insert:: ");
scanf("%d",&value);
push(value);
break;
}
case 2:
{
pop();
break;
}
case 3:
{
display();
break;
}
case 4:
{
exit(0);
}
case 5:
{
printf("%d ",IsEmpty());
break;
}
case 6:
{
printf("%d ",Top());
break;
}
default:
{
printf("invalid!!!!");
}
}
}
}
|
C
|
#include "cairocks.h"
#include <string.h>
typedef struct {
unsigned int last;
unsigned char* data;
} cairocks_read_png_closure_t;
static cairo_status_t cairocks_read_png(
void* closure,
unsigned char* data,
unsigned int length
) {
cairocks_read_png_closure_t* c = (cairocks_read_png_closure_t*)(closure);
memcpy(data, &c->data[c->last], length);
c->last += length;
return CAIRO_STATUS_SUCCESS;
}
cairo_surface_t* cairocks_surface_from_png_data(unsigned char* data) {
cairo_surface_t* surface;
cairocks_read_png_closure_t closure;
closure.last = 0;
closure.data = data;
surface = cairo_image_surface_create_from_png_stream(
cairocks_read_png,
&closure
);
return surface;
}
|
C
|
#include "mk.h"
int
match(char *name, char *template, char *stem, Shell *sh)
{
Rune r;
int n;
while(*name && *template){
n = chartorune(&r, template);
if (PERCENT(r))
break;
while (n--)
if(*name++ != *template++)
return 0;
}
if(!PERCENT(*template))
return 0;
n = strlen(name)-strlen(template+1);
if (n < 0)
return 0;
if (strcmp(template+1, name+n))
return 0;
strncpy(stem, name, n);
stem[n] = 0;
if(*template == '&')
return !sh->charin(stem, "./");
return 1;
}
void
subst(char *stem, char *template, char *dest)
{
Rune r;
char *s;
int n;
while(*template){
n = chartorune(&r, template);
if (PERCENT(r)) {
template += n;
for (s = stem; *s; s++)
*dest++ = *s;
} else
while (n--)
*dest++ = *template++;
}
*dest = 0;
}
|
C
|
/**
* @brief bst header file
* ***/
#include <stdio_ext.h>
#define SIZE 10
///Structure declaration
typedef struct tree
{
struct tree *left;
int data;
struct tree *right;
}bst_t;
char str[SIZE];
int value;
///Prototype of all functions
bst_t* insert_element(bst_t *root);
bst_t* insert_value(bst_t *root, int value);
bst_t* create_node(int value);
void display_tree(bst_t *root);
void in_order(bst_t *root);
void pre_order(bst_t *root);
void post_order(bst_t *root);
void search_tree(bst_t *root);
bst_t* search_element(bst_t *root, int value);
void find_min(bst_t *root);
bst_t* find_min_element(bst_t *root);
bst_t* find_max_element(bst_t *root);
void find_max(bst_t *root);
bst_t* delete_element(bst_t *root);
bst_t* delete_node_val(bst_t *root, int value);
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NUMS 50000
#define TOP_LIMIT 1000
int main()
{
srand(time(NULL));
FILE* f = fopen("../nums.txt", "w");
int i = 0;
for(i = 0; i < NUMS; i++){
fprintf(f, "%d\n", rand()%TOP_LIMIT);
}
fclose(f);
return 0;
}
|
C
|
#pragma once
#include "printer.h"
#include "copier.h"
typedef struct _Node Node;
struct _Node
{
void* data;
Node* next;
};
Node** llist_create();
Node** llist_create_l(int length);
void llist_add(Node** llist, void* data);
void llist_add_i(Node** llist, int index, void* data);
void llist_addAll(Node** llist, Node* other);
void llist_addAll_i(Node** llist, int index, Node* other);
void llist_remove_i(Node** llist, int index);
void llist_remove_e(Node** llist, void* data);
void llist_clear(Node** llist);
int llist_length(Node*);
int llist_exist(Node*, void* data);
Node** llist_copy_deep(Node* llist, copier copier);
void llist_print(Node* node, printer printer);
|
C
|
/*
* File:
* mv_mult_test_mpi.c
*
* Purpose:
* test matrix vector multiplication y=Ax.
* Matrix A is a square matrix of size nxn.
* Column vectors x and y are of size nx1
*
* Input test matrix:
* A[i][j]=c in all positions.
* y[i] is 0 in all positions x[i]= i for 0<=i<n For simplicity,
* we assume n is divisible by no_proc.
*/
#include <math.h>
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include "minunit.h"
int my_rank, no_proc;
MPI_Comm comm;
#define MAX_TEST_MATRIX_SIZE 2048
#define FAIL 0
#define SUCC 1
/*Block mapping functions*/
#define procmap(i, r) ((int)floor((double)i / r))
#define local(i, r) (i % r)
#define TEST_CORRECTNESS 1
#define UPPER_TRIANGULAR 1
int itmv_mult(double local_A[] /* in */, double local_x[] /* in */,
double local_d[] /* in */, double local_y[] /* out */,
double global_x[] /* out */, int matrix_type /* in */,
int n /* in */, int t /* in */, int blocksize /* in */,
int my_rank /* in */, int no_proc /* in */,
MPI_Comm comm /* in */);
int itmv_mult_seq(double A[], double x[], double d[], double y[],
int matrix_type, int n, int t);
void print_error(char *msgheader, char *msg) {
if (my_rank == 0) {
printf("%s Proc 0 error: %s\n", msgheader, msg);
}
}
void print_itmv_sample(char *msgheader, double A[], double x[], double d[],
double y[], int matrix_type, int n, int t) {
printf("%s Test matrix type %d, size n=%d, t=%d\n", msgheader, matrix_type, n,
t);
if (n < 4 || A == NULL || x == NULL || d == NULL || y == NULL) return;
printf("%s check x[0-3] %f, %f, %f, %f\n", msgheader, x[0], x[1], x[2], x[3]);
printf("%s check d[0-3] are %f, %f, %f, %f\n", msgheader, d[0], d[1], d[2],
d[3]);
printf("%s check A[0][0-3] are %f, %f, %f, %f\n", msgheader, A[0], A[1], A[2],
A[3]);
printf("%s check A[1][0-3] are %f, %f, %f, %f\n", msgheader, A[n], A[n + 1],
A[n + 2], A[n + 3]);
printf("%s check A[2][0-3] are %f, %f, %f, %f\n", msgheader, A[2 * n],
A[2 * n + 1], A[2 * n + 2], A[2 * n + 3]);
printf("%s check A[3][0-3] are %f, %f, %f, %f\n", msgheader, A[3 * n],
A[3 * n + 1], A[3 * n + 2], A[3 * n + 3]);
}
void print_itmv_sample_distributed(char *msgheader, double local_A[],
double local_x[], double local_d[],
double local_y[], int matrix_type, int n,
int t, int blocksize) {
int i, local_i;
printf("%s Distributed blocksize=%d matrix type %d, size n=%d, t=%d\n",
msgheader, blocksize, matrix_type, n, t);
if (n < 4) return;
for (i = 0; i < n; i++) {
if (procmap(i, blocksize) == my_rank) {
local_i = local(i, blocksize);
printf("%s Proc %d x[%d] locally x[%d] = %f; d[%d] locally d[%d] = %f\n",
msgheader, my_rank, i, local_i, local_x[local_i], i, local_i,
local_d[local_i]);
printf(
"%s Proc %d Row A[%d] locally A[%d] last 4 elements = %f, %f, %f, "
"%f\n",
msgheader, my_rank, i, local_i, local_A[local_i * n + n - 4],
local_A[local_i * n + n - 3], local_A[local_i * n + n - 2],
local_A[local_i * n + n - 1]);
}
}
}
/*----------------------------------------------------------------------------
* Test if the t iterations of parallel computation {y=Ax; x=y} matches the
* expectation. If failed, return a message string showing the failed point If
* successful, return NULL
*
* In args:
* global_x[] is the array hosted at process 0 storing the final result;
* n is the number of columns (and rows);
* t is the number of iterations conducted;
* matrix_type being 0 means regular matrix;
* matrix_type being 1 (UPPER_TRIANGULAR) means upper triangular.
*
* Return:
* a column vector that contains the final result column vector y.
*
* Note:
* We test only for small n value, and thus we will simplly run
* sequential code to obtain the expected vector and then compare.
*/
double *compute_expected(char *testmsg, int n, int t, int matrix_type) {
int i, j, start;
double *A, *x, *d, *y;
A = malloc(n * n * sizeof(double));
x = malloc(n * sizeof(double));
d = malloc(n * sizeof(double));
y = malloc(n * sizeof(double));
/* Here we assume none of them are NULL. given a modest size n */
for (i = 0; i < n; i++) {
x[i] = 0;
d[i] = (2.0 * n - 1.0) / n;
}
for (i = 0; i < n; i++) {
A[i * n + i] = 0.0;
if (matrix_type == UPPER_TRIANGULAR)
start = i + 1;
else
start = 0;
for (j = start; j < n; j++) {
if (i != j) A[i * n + j] = -1.0 / n;
}
}
#ifdef DEBUG1
print_itmv_sample(testmsg, A, x, d, y, matrix_type, n, t);
#endif
itmv_mult_seq(A, x, d, y, matrix_type, n, t);
free(A);
free(x);
free(d);
return y;
}
char *validate_vect(char *msgheader, double global_x[], int n, int t,
int matrix_type) {
int i;
double *expected;
if (n <= 0) return "Failed: 0 or negative size";
if (n > MAX_TEST_MATRIX_SIZE) return "Failed: Too big to validate";
expected = compute_expected(msgheader, n, t, matrix_type);
for (i = 0; i < n; i++) {
#ifdef DEBUG1
printf("%s Proc 0: i=%d Expected %f Actual %f\n", msgheader, i,
expected[i], global_x[i]);
#endif
mu_assert("One mismatch in iterative mat-vect multiplication",
global_x[i] == expected[i]);
}
free(expected);
return NULL;
}
/*-------------------------------------------------------------------
* Allocate storage space for each array at each processs.
* If failed, 0
* If successful, return 1
*
* In args:
* *local_A is the starting address of local space for matrix A
* with rowwise block mapping;
* *local_x is the starting address of local space for vector x
* with rowwise block mapping;
* *local_d is the starting address of local space for vector d
* with rowwise block mapping;
* *local_y is the starting address of local space for vector y;
* with rowwise block mapping;
* *global_x is the starting address of space for vector x
* with size n blocksize is the size of local array;
* n is the number of columns (and rows).
*/
int allocate_space(double **local_A, double **local_x, double **local_d,
double **local_y, double **global_x, int blocksize, int n) {
int succ = 1, all_succ = 1;
*local_A = malloc(blocksize * n * sizeof(double));
*local_x = malloc(blocksize * sizeof(double));
*local_d = malloc(blocksize * sizeof(double));
*local_y = malloc(blocksize * sizeof(double));
*global_x = malloc(n * sizeof(double));
/* Here we assume none of them are NULL. A more robust program needs to
check the failed memory allocation */
if (*local_A == NULL || *local_x == NULL || *local_d == NULL ||
*local_y == NULL || *global_x == NULL) {
/* Find an error, thus we release space first */
if (*local_A != NULL) free(*local_A);
if (*local_x != NULL) free(*local_x);
if (*local_d != NULL) free(*local_d);
if (*local_y != NULL) free(*local_y);
if (*global_x != NULL) free(*global_x);
succ = 0;
}
/* All processes synchronize to check if there is any failure in allocation
*/
MPI_Allreduce(&succ, &all_succ, 1, MPI_INT, MPI_PROD, comm);
return all_succ;
}
/*-------------------------------------------------------------------
* Initialize test matrix and vectors distributed at each processs.
* vector x of size n: 0 for every element
* vector d of size n: (2n-1)/n for every element
*
* When matrix_type is not UPPER_TRIANGULAR, matrix A of size nxn:
* A[i,i]=0 for diagnal elements. A[i,j]=-1/n for non-diagonal elements.
* When matrix_type is UPPER_TRIANGULAR matrix A of size nxn:
* A[i,i]=0 for diagnal elements. A[i,j]=-1/n for upper diagonal elements
* with i<j all lower triangular elements are 0
*
* In args:
* *local_A is the starting address of local space for matrix A
* with rowwise block mapping, # of rows=blocksize;
* *local_x is the starting address of local space for vector x
* with rowwise block mapping, # of elements=blocksize;
* *local_d is the starting address of local space for vector d
* with rowwise block mapping, # of elements=blocksize;
* *local_y is the starting address of local space for vector y
* with rowwise block mapping, # of elements=blocksize;
* blocksize is the size of local array;
* n is the number of columns (and rows);
* marix_type: matrix type UPP_TRIANGULAR means A is upper triangular
* otherwise just reguar square matrix;
* my_rank: my process ID (started from 0);
*
* Return value:
* If failed, return FAIL (0); If successful, return 1 (SUCC)
*
* Global variable: This function should NOT use any global variable
*/
/*
Block mapping functions
procmap(i, r) ((int)floor((double)i / r))
local(i, r) (i % r)
*/
int init_matrix(double *local_A, double *local_x, double *local_d,
double *local_y, int blocksize, int n, int matrix_type,
int my_rank) {
if (local_A == NULL || local_x == NULL || local_d == NULL ||
local_y == NULL || blocksize <= 0)
return FAIL;
for(int i = 0; i < blocksize; i++){
local_x[i] = 0;
local_d[i] = (2 * n - 1) / (double) n;
}
if(matrix_type != UPPER_TRIANGULAR){
for(int i = 0; i < n; i++){
if(procmap(i, blocksize) == my_rank){
for(int j = 0; j < n; j++){
if(i == j){
local_A[local(i, blocksize) * n + j] = 0;
}else{
local_A[local(i, blocksize) * n + j] = -1 / (double) n;
}
}
}
}
}else{
for(int i = 0; i < n; i++){
if(procmap(i, blocksize) == my_rank){
for(int j = 0; j < n; j++){
if(i >= j){
local_A[local(i, blocksize) * n + j] = 0;
}else{
local_A[local(i, blocksize) * n + j] = -1 / (double) n;
}
}
}
}
}
return SUCC;
}
/*-------------------------------------------------------------------
* Test matrix vector multiplication
* Process 0 collects the error detection. If failed, return a message string
* If successful, return NULL
*/
char *itmv_test(char *testmsg, int test_correctness, int n, int matrix_type,
int t) {
double startwtime = 0, endwtime = 0;
double *local_A, *local_x, *local_d, *local_y, *global_x;
int succ, all_succ, blocksize, i, j, local_i, start;
char *msg;
blocksize = n / no_proc; /* n is divisible by no_proc by assunmption */
succ = allocate_space(&local_A, &local_x, &local_d, &local_y, &global_x,
blocksize, n);
if (succ == 0) { /* one of processes failed in memory
allocation */
msg = "Failed space allocation";
print_error(testmsg, msg);
return msg;
}
succ = init_matrix(local_A, local_x, local_d, local_y, blocksize, n,
matrix_type, my_rank);
#ifdef DEBUG1
print_itmv_sample_distributed(testmsg, local_A, local_x, local_d, local_y,
matrix_type, n, t, blocksize);
#endif
if (my_rank == 0) startwtime = MPI_Wtime();
succ = itmv_mult(local_A, local_x, local_d, local_y, global_x, matrix_type, n,
t, blocksize, my_rank, no_proc, comm);
if (succ == 0) { /* one of processes failed in computing */
msg = "Failed matrix multiplication";
print_error(testmsg, msg);
return msg;
}
if (my_rank == 0) {
endwtime = MPI_Wtime();
printf("%s: Wall clock time = %f at Proc 0 of %d processes\n", testmsg,
endwtime - startwtime, no_proc);
}
msg = NULL;
if (test_correctness == TEST_CORRECTNESS) {
if (my_rank == 0) {
msg = validate_vect(testmsg, global_x, n, t, matrix_type);
if (msg != NULL) print_error(testmsg, msg);
}
}
free(local_A);
free(local_x);
free(local_y);
free(local_d);
free(global_x);
return msg; /* Only process 0 conducts correctness test,
and prints summary report */
}
char *itmv_test1() {
return itmv_test("Test 1", TEST_CORRECTNESS, 4, !UPPER_TRIANGULAR, 1);
}
char *itmv_test2() {
return itmv_test("Test 2", TEST_CORRECTNESS, 4, !UPPER_TRIANGULAR, 2);
}
char *itmv_test3() {
return itmv_test("Test 3", TEST_CORRECTNESS, 8, !UPPER_TRIANGULAR, 1);
}
char *itmv_test4() {
return itmv_test("Test 4", TEST_CORRECTNESS, 8, !UPPER_TRIANGULAR, 2);
}
char *itmv_test5() {
return itmv_test("Test 5", TEST_CORRECTNESS, 4, UPPER_TRIANGULAR, 1);
}
char *itmv_test6() {
return itmv_test("Test 6", TEST_CORRECTNESS, 4, UPPER_TRIANGULAR, 2);
}
char *itmv_test7() {
return itmv_test("Test 7", TEST_CORRECTNESS, 8, UPPER_TRIANGULAR, 1);
}
char *itmv_test8() {
return itmv_test("Test 8", TEST_CORRECTNESS, 8, UPPER_TRIANGULAR, 2);
}
char *itmv_test9() {
return itmv_test("Test 9: n=2K t=1K", !TEST_CORRECTNESS, 2048,
!UPPER_TRIANGULAR, 1024);
}
char *itmv_test10() {
return itmv_test("Test 10: n=2K t=1K upper", !TEST_CORRECTNESS, 2048,
UPPER_TRIANGULAR, 1024);
}
char *itmv_test11() {
return itmv_test("Test 11: n=4K t=1K", !TEST_CORRECTNESS, 4096,
!UPPER_TRIANGULAR, 1024);
}
char *itmv_test12() {
return itmv_test("Test 12: n=4K t=1K upper", !TEST_CORRECTNESS, 4096,
UPPER_TRIANGULAR, 1024);
}
char *itmv_test13() {
return itmv_test("Test 13: n=8K t=1K", !TEST_CORRECTNESS, 4096 * 2,
!UPPER_TRIANGULAR, 1024);
}
char *itmv_test14() {
return itmv_test("Test 14: n=8K t=1K upper", !TEST_CORRECTNESS, 4096 * 2,
UPPER_TRIANGULAR, 1024);
}
/*-------------------------------------------------------------------
* Run all tests. Ignore returned messages.
*/
void run_all_tests(void) {
mu_run_test(itmv_test1);
mu_run_test(itmv_test2);
mu_run_test(itmv_test3);
mu_run_test(itmv_test4);
mu_run_test(itmv_test5);
mu_run_test(itmv_test6);
mu_run_test(itmv_test7);
mu_run_test(itmv_test8);
mu_run_test(itmv_test9); mu_run_test(itmv_test10);
mu_run_test(itmv_test11); mu_run_test(itmv_test12);
mu_run_test(itmv_test13); mu_run_test(itmv_test14);
}
/*-------------------------------------------------------------------
* The main entrance to run all tests.
* Only Proc 0 prints the test summary
*/
void testmain() {
comm = MPI_COMM_WORLD;
MPI_Comm_size(comm, &no_proc);
MPI_Comm_rank(comm, &my_rank);
run_all_tests();
if (my_rank == 0) {
mu_print_test_summary("Summary:");
}
}
|
C
|
/* 8 bit lcd Demo */
// ------- Preamble -------- //
#define F_CPU 1000000L /* atTiny85 Bautrate */
#include <avr/io.h> /* Defines pins, ports, etc */
#include <util/delay.h> /* Functions to waste time */
void pulse_sr(int pin, int t);
void my_delay_ms(int ms);
void init_7_seg(int DS, int CLK, int SHCP);
int DataSignalChannel; // shift register data signal
int ClockChannel; // artificial clock signal for shift register
int ShiftClockChannel; // data out signal for the shift register
//button number
int BTN;
int PAUSE = 1;
int old_state = 0;
// 7 segment display encoding 0-9
int digits[10][8] = {
{1, 1, 1, 1, 1, 1, 1, 0},
{1, 0, 1, 1, 0, 0, 0, 0},
{1, 1, 1, 0, 1, 1, 0, 1},
{1, 1, 1, 1, 1, 0, 0, 1},
{1, 0, 1, 1, 0, 0, 1, 1},
{1, 1, 0, 1, 1, 0, 1, 1},
{1, 1, 0, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 0, 0, 0, 0},
{1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 0, 1, 1}
};
void init_7_seg(int DS, int CLK, int SHCP){
DataSignalChannel = DS;
ClockChannel = CLK;
ShiftClockChannel = SHCP;
}
void push_to_sr(int data[8], int bit_count){
int dp;
for (dp = 0; dp < bit_count; dp++) {
if (data[dp])
PORTB |= (1<<DataSignalChannel);
else
PORTB &= ~(1<<DataSignalChannel);
pulse_sr(ClockChannel, PAUSE);
}
}
int main(void) {
BTN = 3;
init_7_seg(0, 1, 2);
// -------- Inits --------- //
DDRB |= ((1<<DataSignalChannel)|(1<<ClockChannel)|(1<<ShiftClockChannel));
/* Data Direction Register B: set first 3 pins as out. */
while (1) {
int i;
for (i = 0; i < sizeof(digits)/sizeof(digits[0]); i++) {
push_to_sr(digits[i], sizeof(digits[i])/sizeof(digits[i][0]));
pulse_sr(ShiftClockChannel, PAUSE);
while ((PINB & (1<<BTN)) == 0x00){}
}
}
return 0;
}
// pulse function to pulse a pin
// pin - GPIO pin to pulse
// t - pulse delay between high and low
void pulse_sr(int pin, int t){
old_state = PORTB;
PORTB |= (1<<pin);
my_delay_ms(t);
PORTB = old_state;
}
void my_delay_ms(int ms)
{
while (0 < ms)
{
_delay_ms(1);
--ms;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
struct Node {
int value;
struct Node *next;
};
struct LinkedList {
struct Node *head;
};
void init(struct LinkedList *l, const int *a, int n);
void display(struct LinkedList l);
void insert(struct LinkedList *l, int value, unsigned short index);
int delete(struct LinkedList *l, unsigned short index);
int main() {
struct LinkedList list;
init(&list, (int[]) {1, 2, 3, 4, 5}, 5);
display(list);
printf("%d\n", delete(&list, 5));
display(list);
return 0;
}
int delete(struct LinkedList *l, unsigned short index) {
if (l->head) {
struct Node *p = l->head;
struct Node *q = NULL;
if (index == 0) {
if (l->head->next == l->head) {
int deleted = l->head->value;
free(l->head);
l->head = NULL;
return deleted;
} else {
while (p->next != l->head) {
p = p->next;
}
q = l->head;
int deleted = q->value;
p->next = l->head = l->head->next;
free(q);
return deleted;
}
} else {
int i;
for (i = 0; i < index && p->next != l->head; ++i) {
q = p;
p = p->next;
}
if (index == i) {
int deleted = p->value;
q->next = p->next;
free(p);
return deleted;
}
}
}
return INT_MIN;
}
void insert(struct LinkedList *l, int value, unsigned short index) {
if (index == 0) {
struct Node *new = (struct Node *) malloc(sizeof(struct Node));
new->value = value;
if (l->head == NULL) {
new->next = l->head = new;
} else {
struct Node *p = l->head;
while (p->next != l->head) {
p = p->next;
}
new->next = l->head;
l->head = p->next = new;
}
} else if (l->head) {
int i = 0;
struct Node *p = l->head;
struct Node *q = NULL;
while (p->next != l->head) {
q = p;
p = p->next;
if (++i == index) {
struct Node *new = (struct Node *) malloc(sizeof(struct Node));
new->value = value;
new->next = p;
q->next = new;
break;
}
}
if (index == i + 1) {
struct Node *new = (struct Node *) malloc(sizeof(struct Node));
new->value = value;
new->next = l->head;
p->next = new;
}
}
}
void display(struct LinkedList l) {
if (l.head) {
struct Node *p = l.head;
do {
printf("%d ", p->value);
p = p->next;
} while (p != l.head);
printf("\n");
}
}
void init(struct LinkedList *l, const int *a, int n) {
if (n > 0) {
l->head = (struct Node *) malloc(sizeof(struct Node));
l->head->value = a[0];
l->head->next = l->head;
struct Node *prev = l->head;
struct Node *p;
for (int i = 1; i < n; i++) {
p = (struct Node *) malloc(sizeof(struct Node));
p->value = a[i];
p->next = prev->next;
prev->next = p;
prev = prev->next;
}
} else {
l->head = NULL;
}
}
|
C
|
#include <stdio.h>
typedef union float_{ //Estrutura de forma a podermos analisar os bits do float. Usamos uma union do float com um inteiro dividido nas respectivas partes do float
float f; //Valor do float
struct{ //Struct para podermos aceder às respectivas partes de um float
unsigned mantissa:23; //Mantissa do float
unsigned exp:8; //Expoente do float
unsigned signal:1; //Sinal do float
};
}Float;
int round_to_int(float value, int *ivalue){
Float f; //Crição da union auxiliar para analise dos bits do float
f.f=value; //Afetação do campo f da union com o value
if(f.exp-127<=0){ //Caso para quando o expoente é menor ou igual a 127
if(f.exp==127) *ivalue = (f.mantissa & 0x400000)? 2: 1; //Quando o expoente é 127: (-1)^signal * 2^(0) * 1,mantissa = (-1)^signal * (2 caso o primeiro bit da Mantissa seja 1 ou 1 caso esse bit seja 0)
else if(f.exp==126) *ivalue = 1; //Quando o expoente é 126: (-1)^signal * 2^(-1) * 1,mantissa = 1 pois temos sempre o bit que vale 0.5 a 1, devido ao shift para a direita (1,mantissa)>>1 = 0,5+mantissa
else *ivalue = 0; //Quando o expoente é menor que 126 dá sempre 0 pois nunca iremos ter o bit de que vale 0,5 a 1
}else if(f.exp-127==128) return -1; //Quando o expoente é 255 dá erro pois ou dá infinito/-infinito ou NaN logo retorna -1(erro)
else{ //Caso para quando o expoente é maior que 127
if(f.mantissa==0) *ivalue = (1<<(f.exp-127)); //Quando a mantissa é 0: (-1)^signal * 2^(exp-127) * 1,0
else{ //Caso para quando o expoente é maior que 127 e a mantissa não é 0
int aux = 0x800000 | f.mantissa; //Acrescentar 1 bit à esquerda da mantissa, de forma a ser 1,mantissa
int xp = f.exp-127; //Calcular o expoente-127
if(xp<23){ //Caso para quando o expoente-127 é menor que 23
*ivalue = ((aux>>(23-xp-1))&1)? (aux>>(23-xp))+1 : aux>>(23-xp);//Quando o expoente-127 é menor que 23 o valor é simplesmente 1,mantissa shiftado xp posições para direita, +1 caso o último shift der carry
}else *ivalue = aux<<(xp-23); //Quando o expoente-127 é maior ou igual a 23 basta shiftar 1,mantissa xp-23 posições para a esquerda.
}
}
*ivalue *= (f.signal? -1: 1); //Colocar o valor final a negativo caso o value seja negativo
return 0; //Retorno de 0 quando value é convertido correctamente
}
int main(){ //Teste da função round_to_int
float f = 2.5;
int a;
printf("%d\n", round_to_int(f, &a)); //Print do retorno da função, de forma a ver se deu erro ou converteu
printf("%d\n", a); //Print do valor convertido
}
|
C
|
#include "sort.h"
/**
* bubble_sort - function that sorts an array of integers
* in ascending order using the Bubble sort algorithm
* @array: array of integers
* @size: lenght of array
* Return: none
*/
void bubble_sort(int *array, size_t size)
{
size_t i, aux;
int bandera = 1;
if (!array || !size)
return;
while (bandera != 0)
{
bandera = 0;
for (i = 1; i < size; i++)
{
if (array[i - 1] > array[i])
{
aux = array[i];
array[i] = array[i - 1];
array[i - 1] = aux;
print_array(array, size);
bandera = 1;
}
}
}
}
|
C
|
#include<stdio.h>//ѭ
int main(void)
{
int n = 0;
while (n < 3)
printf("n is %d\n", n);
n++;
printf("That's sll this program does.\n");
return 0;
}
|
C
|
/*
* Renan Santana / PID: 4031451 / HW1 / DUE: OCT 14, 2014
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
//
#include <dirent.h>
//#include <sys/stat.h> // change write permission
#include <errno.h>
//
void syserr(char* msg) { perror(msg); exit(-1); }
char* requestData(char* request, int sockfd){
int n;
n = send(sockfd, request, 255, 0);
if(n < 0) { syserr("Err 1.1: Can't Send To Server"); }
n = recv(sockfd, request, 255, 0);
if(n < 0){ syserr("Err 1.2: Can't Receive From Server"); }
return request;
}
void lslocal(){
int n;
DIR *dir;
struct dirent *elm;
if((dir = opendir("./ClientFiles")) != NULL){
while((elm = readdir(dir)) != NULL){ printf("%s\n", elm->d_name); }
closedir(dir);
}
else{ perror("Can't open directory: "); }
}
void lsremote(int sockfd, char token1[]){
int n;
char buffer[128];
// get approval from server
char* fileName = requestData(token1, sockfd);
if(fileName[0] == '\0'){ printf("No File Existance In Server\n"); }
else{
// receive the list of file one be one
while((n = recv(sockfd, buffer, 127, 0)) > 0){
if(buffer[0] == '\0'){ break; }
buffer[n] = '\0';
printf("%s\n", buffer);
}
if(n < 0) { syserr("Err 2.1: Can't Receive From Server"); }
}
}
void put(int sockfd, char buffer2[], char token2[]){
int n, size, fileSize;
char tempVar[128];
char fileName[128];
char cat[128];
unsigned char buffer[1024];
unsigned short int found = 0;
FILE *fp;
DIR *dir;
struct dirent *elm;
requestData(buffer2, sockfd);
if((dir = opendir("./ClientFiles")) != NULL){
// send to the client directory is valid
tempVar[0] = '0';
n = send(sockfd, tempVar, 127, 0);
if(n < 0) { syserr("Err 2.1: Can't Send To Server"); }
while((elm = readdir(dir)) != NULL){
strcpy(fileName, elm->d_name);
if(strcmp(fileName, token2) == 0){ found = 1; break; }
}
closedir(dir);
if(found){
bzero(cat, 128);
strcat(cat, "./ClientFiles/");
strcat(cat, token2);
fp = fopen(cat, "rb");
if(fp == NULL){ perror("Bad File Name: "); exit(1); }
//Get file length
bzero(tempVar, 127);
fseek(fp, 0, SEEK_END);
fileSize = ftell(fp);
fseek(fp, 0, SEEK_SET);
sprintf(tempVar, "%i", fileSize);
// send to the client that we found the file
n = send(sockfd, tempVar, 127, 0);
if(n < 0) { syserr("Err 2.2: Can't Send To Server"); }
do {
size = fread(buffer, sizeof(unsigned char), sizeof(buffer), fp);
if(size < sizeof(buffer)){
n = send(sockfd, buffer, size, 0);
if(n < 0) { syserr("Err 2.3: Can't Send To Server"); }
}
else{
n = send(sockfd, buffer, 1024, 0);
if(n < 0) { syserr("Err 2.3: Can't Send To Server"); }
}
bzero(buffer, 1023);
} while (size == sizeof(buffer)); // if it was a full buffer, loop again
printf("Upload '%s' to remote server: successful\n", token2);
fclose(fp);
}
else{
printf("File '%s' at client was not found.\n", token2);
tempVar[0] = '\0';
n = send(sockfd, tempVar, 127, 0);
if(n < 0) { syserr("Err 2.5: Can't Send To Server"); }
}
}
else{
closedir(dir);
printf("Can't open directory\n");
tempVar[0] = '\0';
n = send(sockfd, tempVar, 127, 0);
if(n < 0) { syserr("Err 2.6: Can't Send To Server"); }
}
}
void get(int sockfd, char buffer2[], char token2[]){
int n, fileSize, amountWrote;
char cat[128];
char buffer[256];
unsigned char fileBuffer[1024];
FILE *fp;
// first check : make sure the directory is valid
char* boolFile = requestData(buffer2, sockfd);
if(boolFile[0] != '\0'){
// second check : make sure the file exist
n = recv(sockfd, buffer, 255, 0);
if(n < 0) { syserr("Err 3.1: Can't Receive From Server"); }
if(buffer[0] != '\0'){
buffer[n] = '\0';
fileSize = atoi(buffer);
bzero(cat, 127);
strcat(cat, "./ClientFiles/");
strcat(cat, token2);
//Open file "+" create file if not existing
fp = fopen(cat, "w+b");
if (fp == NULL){
perror("FP NULL: ");
strerror(errno);
exit(1);
}
do{
if(fileSize < sizeof(fileBuffer)){
n = recv(sockfd, fileBuffer, fileSize, 0);
if(n < 0) { syserr("Err 3.2: Can't Receive From Server"); }
}
else{
n = recv(sockfd, fileBuffer, 1024, 0);
if(n < 0) { syserr("Err 3.2: Can't Receive From Server"); }
}
fwrite(fileBuffer, sizeof(unsigned char), n, fp);
fileSize -= n;
bzero(fileBuffer, 1024);
}while(fileSize > 0);
printf("Retrieve '%s' from remote server: successful\n", token2);
fclose(fp);
}
else{ printf("File '%s' at remote server was not found.\n", token2); }
}
else{ printf("Directory in Server is invalid.\n"); }
}
int main(int argc, char* argv[]){
int sockfd, portno, n;
struct hostent* server;
struct sockaddr_in serv_addr;
char token1[32], token2[32], inputLine[32];
char buffer[256];
if(argc != 3) {
if(argc == 2){
portno = 5555;
}
else{
fprintf(stderr, "Usage: %s <hostname> <port>\n", argv[0]);
return 1;
}
}
else{ portno = atoi(argv[2]); }
server = gethostbyname(argv[1]);
if(!server) {
fprintf(stderr, "ERROR: no such host: %s\n", argv[1]);
return 2;
}
sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(sockfd < 0) { syserr("can't open socket"); }
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr = *((struct in_addr*)server->h_addr);
serv_addr.sin_port = htons(portno);
if(connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)
syserr("Can't connect to server.");
printf("Connection to %s:%i established. Now awaiting commands...\n", argv[1], portno);
snprintf(inputLine, sizeof(inputLine), "%s:%i>",argv[1], portno);
while(1){
printf("%s ",inputLine);
fgets(buffer, 255, stdin);
n = strlen(buffer);
if(n > 0 && buffer[n-1] == '\n') { buffer[n-1] = '\0'; }
// parse the string
sscanf(buffer, "%s %s", token1, token2);
// Fit the token in one of these commands
if(strcmp("ls-local",token1) == 0){ lslocal(); }
else if(strcmp("ls-remote",token1) == 0){ lsremote(sockfd, buffer); }
else if(strcmp("put",token1) == 0){ put(sockfd, buffer, token2); }
else if(strcmp("get",token1) == 0){ get(sockfd, buffer, token2); }
else if(strcmp("exit",buffer) == 0){ requestData(buffer, sockfd); break; }
else { puts("Input is not valid."); }
memset(buffer, 0, sizeof(buffer));
memset(token1, 0, sizeof(token1));
memset(token2, 0, sizeof(token2));
}
printf("Connection to server %s terminated. Bye now!\n", inputLine);
close(sockfd);
return 0;
}
|
C
|
#include<stdio.h>
int main(){
int n,i,sum = 0,c,a[1000];
scanf("%d",&n);
//best way for this question
/*
for(i = 0; i < n; ++i){
scanf("%d",&c);
sum = sum + c;
}
*/
for(i = 0; i < n; ++i){
scanf("%d",&a[i]);
}
for(i = 0; i < n; ++i){
sum = sum + a[i];
}
printf("%d",sum);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void initHist(int tabHistAns[12][4], char tabHistHint[12][4], char waiting);
void printHist(int tabHistAns[12][4], char tabHistHint[12][4]);
void rules(char wrong, char almost, char good);
void insertAnswer(int tabHistAns[12][4], char sTry[5], int round);
void checking(int tabHistAns[12][4], char tabHistHint[12][4], char wrong, char almost, char good, int value1, int value12, int value13, int value14, int round);
int main()
{
const int MIN = 0, MAX = 9;
char cWrong = '_', cAlmost = '-', cGood = '=', cWaiting = '.', sTry[5], histHint[12][4];
int histAns[12][4], gameEnd=0, round;
//Init secret code
srand(time(NULL));
int n1 = (rand()%(MAX-MIN+1))+MIN;
int n2 = (rand()%(MAX-MIN+1))+MIN;
int n3 = (rand()%(MAX-MIN+1))+MIN;
int n4 = (rand()%(MAX-MIN+1))+MIN;
//Init historics of inputs and of feedbacks
initHist(histAns, histHint, cWaiting);
//Prints rules and indications
rules(cWrong, cAlmost, cGood);
//Prints both historics
printHist(histAns, histHint);
//Instructions just for debug
//printf("code pour debug : %d %d %d %d \n", n1, n2, n3, n4);
//Reads and inserts input into inputs historic
for (round = 0; round < 12; round++)
{
scanf("%s", sTry);
//Inserts the input into histAns
insertAnswer(histAns, sTry, round);
system("cls" );
rules(cWrong, cAlmost, cGood);
//Checks the current input and fills the feedback historic tab
checking(histAns, histHint, cWrong, cAlmost, cGood, n1, n2, n3, n4, round);
if (histHint[round][0]==cGood && histHint[round][1]==cGood && histHint[round][2]==cGood && histHint[round][3]==cGood)
{
gameEnd=1;
break;
}
printHist(histAns, histHint);
//Instruction for debug
//printf("code debug : %d%d%d%d \n\n", n1, n2, n3, n4);
}
//Checks victory condition and indicates if the player won plus additional informations
if (gameEnd==1)
{
printHist(histAns, histHint);
printf("You find the code with %d try! It was %d%d%d%d \n", round+1, n1, n2, n3, n4);
}
else if (gameEnd!=1)
{
printf("You lose ! It was %d%d%d%d \n", n1, n2, n3, n4);
}
return 0;
}
void initHist(int tabHistAns[12][4], char tabHistHint[12][4], char waiting)
{
for (int i = 0; i < 12; i++)
{
for (int j = 0; j < 4; j++)
{
//Init the Answers historic
tabHistAns[i][j]=0;
//Init the Hints historic
tabHistHint[i][j]=waiting;
}
}
}
void printHist(int tabHistAns[12][4], char tabHistHint[12][4])
{
int i, j;
printf(" + ~ ~ ~ ~ + ~ ~ ~ ~ +\n");
for (i = 0; i < 12; i++)
{
printf(" | ");
//Prints the left part of the UI with answers and previous answers
for (j = 0; j < 4; j++)
{
printf("%d ", tabHistAns[i][j]);
}
printf("| ");
//Prints the right part of the UI with hints and previous hints
for (j = 0; j < 4; j++)
{
printf("%c ", tabHistHint[i][j]);
}
printf("|\n");
}
printf(" + ~ ~ ~ ~ + ~ ~ ~ ~ +\n\n");
}
void rules(char wrong, char almost, char good)
{
printf("Wanna try to crack the code ?\n");
printf("Then give a 4 digits number and see if you can find the good one.\n\n");
printf("%c : number not in the code\n%c : number in the code but not at the good position\n%c : good number at the right position\n\n", wrong, almost, good);
}
void insertAnswer(int tabHistAns[12][4], char sTry[5], int round)
{
for (int j = 0; j < 4; j++)
{
switch (sTry[j])
{
case '0':
tabHistAns[round][j] = 0;
break;
case '1':
tabHistAns[round][j] = 1;
break;
case '2':
tabHistAns[round][j] = 2;
break;
case '3':
tabHistAns[round][j] = 3;
break;
case '4':
tabHistAns[round][j] = 4;
break;
case '5':
tabHistAns[round][j] = 5;
break;
case '6':
tabHistAns[round][j] = 6;
break;
case '7':
tabHistAns[round][j] = 7;
break;
case '8':
tabHistAns[round][j] = 8;
break;
case '9':
tabHistAns[round][j] = 9;
break;
default:
tabHistAns[round][j] = 0;
break;
}
}
}
void checking(int tabHistAns[12][4], char tabHistHint[12][4], char wrong, char almost, char good, int value1, int value2, int value3, int value4, int round)
{
for (int j = 0; j < 4; j++)
{
//initiate the case where all numbers are wrong
if (tabHistAns[round][j]!=value1 && tabHistAns[round][j]!=value2 && tabHistAns[round][j]!=value3 && tabHistAns[round][j]!=value4)
{
tabHistHint[round][j]=wrong;
}
//check if the number is in the secret code
if (tabHistAns[round][j]==value1 || tabHistAns[round][j]==value2 || tabHistAns[round][j]==value3 || tabHistAns[round][j]==value4)
{
tabHistHint[round][j]=almost;
}
//check if the number is rightly place
if (tabHistAns[round][0]==value1)
{
tabHistHint[round][0]=good;
}
if (tabHistAns[round][1]==value2)
{
tabHistHint[round][1]=good;
}
if (tabHistAns[round][2]==value3)
{
tabHistHint[round][2]=good;
}
if (tabHistAns[round][3]==value4)
{
tabHistHint[round][3]=good;
}
}
}
|
C
|
#include "q.h"
void start_thread(void (*function)(void))
{
void * stack = (void *) malloc(8192);
TCB_t * tcb = (TCB_t *) malloc(sizeof(TCB_t));
init_TCB(tcb, function, stack, 8192);
AddQueue(RunQ, tcb);
}
void run()
{
TCB_t * Curr_Thread = RunQ->head;
ucontext_t parent; // get a place to store the main context, for faking
getcontext(&parent); // magic sauce
swapcontext(&parent, &(Curr_Thread->context)); // start the first thread
}
void yield()
{
ucontext_t current;
getcontext(¤t);
RunQ->head->context = current;
RotateQ(RunQ);
ucontext_t new_context = RunQ->head->context;
swapcontext(¤t, &new_context);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "lib/linear-search.h"
void menu(){
int option=0;
do{
printf("\n-------------------------------\n");
printf(" Linear Search :D\n");
printf("1. Print the array\n");
printf("2. Change values on the array\n");
printf("3. Search a value in the array\n");
printf("4. Leave\n");
printf("-------------------------------\n");
printf("Choose your option:");
scanf("%i", &option);
printf("\n");
switch(option){
case 1:
printfArray();
break;
case 2:
getArray();
break;
case 3:
search();
break;
case 4:
printf("Thanks for using :D");
break;
default:
printf("Invalid option");
}
if ((option != 1) && (option != 2)) {
printf("\n");
}
} while (option != 4);
}
int main (){
menu();
return 0;
}
|
C
|
/*
** list.c for in /home/planch_j/rendu/CPE/CPE_2015_corewar/corewar/parsing/src/
**
** Made by Jean PLANCHER
** Login <planch_j@epitech.net>
**
** Started on Sun Mar 27 06:14:14 2016 Jean PLANCHER
** Last update Sun Apr 24 02:54:05 2016 Jean PLANCHER
*/
#include "my.h"
t_list *create_list(void)
{
t_list *list;
list = my_malloc(sizeof(t_list));
list->first = NULL;
list->length = 0;
return (list);
}
void add_start(t_list **list, char **data)
{
t_element *tmp;
tmp = my_malloc(sizeof(t_element));
tmp->data = data;
tmp->next = (*list)->first;
(*list)->first = tmp;
(*list)->length++;
}
void add_end(t_list **list, char **data)
{
t_element *tmp;
t_element *temp;
tmp = my_malloc(sizeof(t_element));
tmp->data = data;
temp = (*list)->first;
if (!temp)
{
(*list)->first = tmp;
}
else
{
while (temp->next)
temp = temp->next;
temp->next = tmp;
}
tmp->next = NULL;
(*list)->length++;
}
void del_list(t_list **list)
{
t_element *tmp;
char **temp;
int i;
while ((*list)->first != NULL)
{
tmp = (*list)->first->next;
temp = (char **)(*list)->first->data;
i = -1;
while (temp[++i])
free(temp[i]);
free((*list)->first->data);
free((*list)->first);
(*list)->first = tmp;
(*list)->length--;
}
free((*list));
}
|
C
|
#include <std.h>
#include "../antioch.h"
inherit VAULT;
void create()
{
::create();
set_terrain(STONE_BUILDING);
set_travel(DIRT_ROAD);
set_property("indoors",1);
set_property("light",2);
set_property("no sticks",1);
set_short("The Royal Kitchen");
set_long(
"This is the extravagent kitchen of the Antioch palace. It is here where"+
" the great chefs prepare the meals for the balls and banquets. The room"+
" is large with many ovens, stoves, and counters. Bowls and cooking"+
" utensils of all sorts are found in the cupboards, used for creating"+
" normal dishes to any foreign delicacy a visiting ambassador might wish."+
" The kitchen is currently lightly staffed, and there is always something"+
" cooking here in case the palace residents should get hungry. There is"+
" some sort of stew simmering in a large pot on one of the stoves."+
" Freshly baked bread is covered by a towel on the counter to keep it"+
" warm, and there is more baking in the oven. There are a few piping hot"+
" pies of different varieties that have been set out to cool. Sliced"+
" fruits and chopped vegetables are laid out on platters, along with"+
" slices of bread and cheese. The kitchen has been cleverly designed to"+
" allow for maximum capacity, with an island of stoves and ovens in the"+
" center and counters and sinks around the edges. On the eastern side"+
" of the room there is even a large fire pit for smoking meat, along with"+
" a vent that releases all the smoke outside, instead of choking the room"+
" with it. This is a very nice kitchen."
);
set_smell("default","You smell all sorts of delicious foods here.");
set_listen("default","The stew slowly simmers on the stove.");
set_items(([
({"counter","counters"}) : "There are clean counter tops spanning most"+
" of the kitchen. Some freshly baked bread is on one side, next to hot"+
" pies, and plates of chopped fruits and vegetables, along with platters"+
" of bread, meats, and cheeses.",
({"oven","ovens","stove","stoves"}) : "Large brick ovens take up the"+
" center space of the room. On top of each is either a spit, metal grill,"+
" or flat metal surface that serves as a stove. The spits are best for"+
" roasting meat on, giving it a delicious flavor. The metal grill with"+
" a small fire beneath allows for quick cooking. The surface of flat"+
" metal is a slightly newer invetion, kept warm by the heated oven beneath"+
" it, it is where the stew pots are placed to allow them to keep warm.",
({"pot","pots","kettle","kettles","utensils","bowls","dishes","cupboards"}) : "All"+
" sorts of cooking utensils can be found around the room. Bowls and dishes"+
" are kept in the cupboards, many pots and kettles are simmering on the"+
" stoves, and the cooking utensils are kept in drawers around the room.",
({"plate","plates","platters"}) : "Platters of food are laid out on the"+
" counter for the palace staff. There are plates of sliced fruits and"+
" vegetables, along with platters of thinly cut cheeses, meats, and breads.",
({"bread","fresh bread"}) : "Some freshly baked bread is sitting on the"+
" counter, covered by a towel to keep it nice and hot. With a bit of"+
" butter melted onto it, it's a great snack.",
({"pie","pies","hot pies","piping hot pies"}) : "Several delicious"+
" smelling pies have been left out on the counter to cool. You can see"+
" the steam rising from them. There are a couple varieties, ranging"+
" from apple to strawberry, to blackberry. They look quite good.",
({"meat","meats","cheese","cheeses","sliced meats","sliced bread","sliced cheese","sliced meat","sliced cheeses"}) : "A"+
" plate of thinly sliced meats, breads, and cheeses has been left out for"+
" the palace staff to snack on.",
({"fruit","fruits","sliced fruits","vegetables","chopped vegetables"}) : "A"+
" plate of sliced fruits and chopped vegetables has been beautifully"+
" arranged. The fruits don't have a spot on them, and the vegetables"+
" look fresh. Both appear to have been chilled for a little while.",
"floor" : "The floor here is made out of some black stone that is"+
" supposed to stay cool. It will help to keep any fires from spreading,"+
" as well as keep the kitchen cooler when the ovens are on. It appears"+
" quite spotless.",
"ceiling" : "The ceiling is rather unremarkable. There are a few soot"+
" stains on it from the stoves, but it looks as though it is cleaned"+
" quite regularly.",
({"sink","sinks"}) : "There are several large sinks around the room. They"+
" are of the best magical quality. You have only to turn the knobs for"+
" hot or cold water to come splashing out.",
"stew" : "There are a couple large pots of stew simmering on the stoves.",
"fire pit" : "On the eastern side of the room is a large fire pit with"+
" a spit on it. It is used for roasting the larger animals, such as pig"+
" or wild turkey. There is a vent next to the fire pit that sucks the"+
" smoke out of the room, keeping the air in the kitchen clean.",
"vent" : "A large vent on the eastern wall allows for the smoke to escape"+
" outside instead of filling up the room.",
]));
set_exits(([
"south" : ROOMS+"pal3",
]));
set_door("kitchen door",ROOMS+"pal3","south",0);
}
void reset()
{
::reset();
if(!present("vardot")) {
new(MONS+"chef")->move(TO);
}
return;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// Functions Declaring
void writeStringToTextFile(char filePath[50], char str[50]);
// Function: Read a string from a text file: CHUA DUOC
// const char *getName()
// {
// return "Belly";
// }
// main function
int main()
{
// WRITE A STRING TO A TEXT FILE
char filePath[50] = "D:\\output.txt";
char name[50];
printf("Enter your name: ");
fgets(name, sizeof(name), stdin); // Use fgets() function to get string entered by user
// Calling function writeStringToTextFile() to write a string to a text file
writeStringToTextFile(filePath, name);
printf("Wrote your name to %s !", filePath);
}
// Function: Write a string to a text file
void writeStringToTextFile(char filePath[50], char str[50])
{
FILE *fp;
fp = fopen(filePath, "w");
fprintf(fp, "%s", str); // Use fprintf() function to write a string to a text file
fclose(fp);
}
|
C
|
#ifndef SETTINGS_H_
#define SETTINGS_H_
///-------------INCLUSION DE BIBLIOTECAS-------------///
//------BIBLIOTECAS EXTERNAS------//
#include <pthread.h>
#include "unistd.h"
#include "sys/inotify.h"
//------BIBLIOTECAS INTERNAS------//
#include "kemmens/config.h"
#include "kemmens/logger.h"
#include "kemmens/ThreadPool.h"
#include "kemmens/CommandInterpreter.h"
#include "kemmens/SocketClient.h"
//------BIBLIOTECAS PROPIAS------//
///-------------ESTRUCTURAS DEFINIDAS-------------///
/*
* Estructura para guardar los datos de configuracion del SAFA, levantados del SAFA.config
* CAMPOS:
* puerto: Puerto de escucha de conexiones (el SAFA es servidor universal)
* algoritmo: Nombre del algoritmo de planificacion del PCP; puede ser "RR", "VRR" o "PROPIO" (IOBF)
* quantum: Quantum maximo de ejecucion que puede llevar a cabo un DTB; sirve para todos los algoritmos
* multiprogramacion: Grado de multiprogramacion del sistema (cuantos procesos puede haber en memoria)
* retardo: Retardo, en milisegundos, que sufre cada ciclo de planificacion (del PCP?)
*/
struct Configuracion_s
{
int puerto;
char* algoritmo;
int quantum;
int multiprogramacion;
int retardo;
} typedef Configuracion;
///-------------CONSTANTES DEFINIDAS-------------///
#define RUTA_CONFIG "Config/SAFA.config"
#define RUTA_WATCHABLE "Config"
//Para los eventos de inotify; maximo numero de cambios a registrar, largo del nombre del archivo, tamanios de evento y buffer
#define MAX_CHANGES_ALLOWED 1024
#define FILE_LENGTH 14
#define EVENT_SIZE ( sizeof (struct inotify_event) )
#define BUFFER_SIZE ( MAX_CHANGES_ALLOWED * ( EVENT_SIZE + FILE_LENGTH ))
//Tipos de cambio de algoritmo del PCP, a ver en la ejecucion del mismo
#define ALGORITHM_CHANGE_UNALTERED 40
#define ALGORITHM_CHANGE_RR_TO_VRR 41
#define ALGORITHM_CHANGE_RR_TO_OWN 42
#define ALGORITHM_CHANGE_VRR_TO_RR 43
#define ALGORITHM_CHANGE_VRR_TO_OWN 44
#define ALGORITHM_CHANGE_OWN_TO_RR 45
#define ALGORITHM_CHANGE_OWN_TO_VRR 46
///-------------VARIABLES GLOBALES-------------///
/*extern*/ Configuracion* settings; //Almacena los datos de configuracion
//No es extern porque no sera modificada en otros modulos
pthread_mutex_t mutexSettings; //Mutex para excluir el acceso a los parametros de configuracion;
//es por si se los consulta mientras se los esta modificando
//extern en Scheduling.h, CH.h
int algorithmChange; //Codigo de cambio de algoritmos; extern en Scheduling.h
///-------------FUNCIONES DEFINIDAS------------///
/*
* ACCION: Mallocear la estructura de settings y cargarla con los datos del archivo de configuracion
* Debe llamarse a esta funcion al arrancar el programa, antes que nada
*/
void Configurar();
/*
* ACCION: Actualizar los datos de las variables de configuracion (excepto el puerto), sin mallocear
* Esta funcion es llamada desde el monitor del archivo, ejecutado en un thread
*/
void UpdateSettings();
/*
* ACCION: Monitorear el archivo de SAFA.config ante eventuales cambios en su contenido
* Esta funcion debe ser ejecutada en un hilo aparte, posee el read que es bloqueante
*/
void MonitorConfigFile();
/*
* ACCION: Liberar la memoria de la estructura de configuracion, sus campos, y el mutex de acceso a la misma
*/
void DeleteSettingsVariables();
#endif /* SETTINGS_H_ */
|
C
|
// Average of positive numbers
#include <stdio.h>
void main()
{
int n,i, nsum = 0, psum = 0, pcount = 0, ncount = 0;
for(i = 1; i <= 5; i ++)
{
printf("Enter a number:");
scanf("%d",&n);
if(n >= 0)
{
psum += n;
pcount ++;
}
else
{
nsum += n;
ncount ++;
}
}
printf("Positive Average = %d, Negative Average : %d",psum/pcount, nsum/ncount);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(void)
{
int listenfd, connfd;
struct sockaddr_in servaddr;
char buf[1024];
listenfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(1234);
bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr));
listen(listenfd, 5);
while(1)
{
connfd = accept(listenfd, NULL, NULL);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 976
#define SLEEP -1
#define WAKE_UP -2
typedef struct _Guard {
int id;
int asleep[60];
int max_minutes;
int i_max_minutes;
struct _Guard *next;
} Guard;
Guard *new_guard(int id) {
Guard *g = malloc(sizeof(Guard));
g->id = id;
g->max_minutes = 0;
g->i_max_minutes = 0;
g->next = NULL;
memset(g->asleep, 0, 60 * sizeof(int));
return g;
}
int get_minute(char date[17]) {
return atoi(date + 14);
}
int main() {
char dates[LEN][17];
int actions[LEN];
for (int i = 0; i < LEN; ++i) {
char date_time[6];
char text[8];
char dump[8];
scanf("[%10s %5s] %s %s", dates[i], date_time, dump, text);
strcat(dates[i], " ");
strcat(dates[i], date_time);
if (strcmp(text, "asleep") == 0) {
actions[i] = SLEEP;
} else if (strcmp(text, "up") == 0) {
actions[i] = WAKE_UP;
} else {
actions[i] = atoi(text + 1);
}
int j = i;
while (j > 0 && strcmp(dates[j], dates[j-1]) < 0) {
char date_temp[17];
strcpy(date_temp, dates[j-1]);
strcpy(dates[j-1], dates[j]);
strcpy(dates[j], date_temp);
int id_temp = actions[j-1];
actions[j-1] = actions[j];
actions[j] = id_temp;
j--;
}
while (getchar() != '\n'); // Move to the next line
}
Guard *first = NULL;
Guard *current = NULL;
int sleep_minute, wake_up_minute;
for (int i = 0; i < LEN; ++i) {
if (actions[i] == SLEEP) {
sleep_minute = get_minute(dates[i]);
} else if (actions[i] == WAKE_UP) {
wake_up_minute = get_minute(dates[i]);
for (int j = sleep_minute; j < wake_up_minute; ++j) {
current->asleep[j]++;
if (current->asleep[j] > current->max_minutes) {
current->max_minutes = current->asleep[j];
current->i_max_minutes = j;
}
}
} else {
if (first == NULL) {
first = new_guard(actions[i]);
current = first;
} else {
current = first;
while (current->next != NULL) {
if (current->id == actions[i])
break;
current = current->next;
}
if (current->id != actions[i]) {
current->next = new_guard(actions[i]);
current = current->next;
}
}
}
}
Guard *max = first;
current = first->next;
while (current != NULL) {
if (current->max_minutes > max->max_minutes)
max = current;
current = current->next;
}
int result = max->id * max->i_max_minutes;
printf("Result: %d\n", result);
return 0;
}
|
C
|
/*
* playPokerMain.c
* This is a simple program that plays a draw poker game. You're dealt 5 cards then you get to choose which cards to keep
* and which cards to give up. Then you get new cards and your payout is set based on the value of your hand. You're then given
* the option to continue.
* Created on: Jan 12, 2019
* Author: Adriel Perkins
*/
#include "playPoker.h"
//Getting into the practice of always prototyping your functions for consistency. Default is integer, but best to declare anyway.
void printGreeting();
int getBet();
char getSuit(int suit);
char getRank(int rank);
void getFirstHand(int cardRank[], int cardSuit[]);
void getFinalHand(int cardRank[], int cardSuit[], int finalRank[],
int finalSuit[], int ranksInHand[], int suitsInHand[]);
int analyzeHand(int ranksInHand[], int suitsInHand[]);
int main(int argc, const char * argv[]) {
//declare variables that will be needed for main program
int bet;
int bank = 100;
int i;
int cardRank[5];//1 of 13 values for Ace through King
int cardSuit[5];//1 of 4 values for clubs, diamonds, hearts, and spades
int finalRank[5];
int finalSuit[5];
int ranksInHand[13];
int suitsInHand[4];
int winnings;
time_t t;
char suit, rank, stillPlaying;
printGreeting();
//going to make a do - while loop for the game to play dependent on how much the user wants to play
do {
bet = getBet();
srand(time(&t));
getFirstHand(cardRank, cardSuit);
printf("Your five cards are \n");
for (i = 0; i < 5; i++) {
suit = getSuit(cardSuit[i]);
rank = getRank(cardRank[i]);
printf("Card #%d is %c %c\n", i+1, suit, rank);
}
//going to figure out the value of the hand by using two arrays. each array has to be zeroed out since the player can play multiple hands
for (i=0; i <4; i++){
suitsInHand[i] =0;
}
for (i = 0; i <13; i++){
ranksInHand[i] = 0;
}
getFinalHand(cardRank, cardSuit, finalRank, finalSuit, ranksInHand, suitsInHand);
printf("Your 5 final cards are:\n");
for (i = 0; i < 5; ++i) {
suit = getSuit(finalSuit[i]);
rank = getRank(finalRank[i]);
printf("Card #%d: %c %c\n", i+1, suit, rank);
}
winnings = analyzeHand(ranksInHand, suitsInHand);
printf("You won %d!\n", bet*winnings);
bank = bank - bet + (bet*winnings);
printf("\nYour bank is now at %d", bank);
printf("\nDo you want to play again? (Y/N");
scanf(" %c", &stillPlaying);
} while (toupper(stillPlaying) == 'Y');
return 0;
}
//functions
//below is the printGreetting() function that prints the information you see at the very beginning of the game.
void printGreeting(){
printf("Greetings!!! - Are you ready to play some Poker?!\n");
printf("*************************************************\n");
printf("Here are the rules...\n");
printf("You start with 100 chips, and make a bet from 1 to 5 chips.\n");
printf("You're dealt 5 cards, and then you get to choose which cards you want to keep and which ones you want to get rid of. \n");
printf("You want to make the best possible hand so that you can WIN!!\n");
printf("Here is the table for winnings if you bet 1 chip.\n\n");
printf("\nPair\t\t1 chips");
printf("\nTwo pairs\t\t2 chips");
printf("\nThree of a kind\t\t3 chips");
printf("\nA Straight\t\t4 chips");
printf("\nA flush\t\t5 chips");
printf("\nA full house\t\t8 chips");
printf("\nFour of a kind\t\t10 chips");
printf("\nA Straight Flush\t\t20 chips");
printf("\nNow, it's time to have some fun!!");
}
//below is the getFirstHand() function that deals the first 5 cards of the game.
void getFirstHand(int cardRank[], int cardSuit[]){
int i, j;
int duplicateCard;
for (i = 0; i < 5; i++){
duplicateCard = 0;
do {
cardRank[i] = (rand() % 13);
cardSuit[i] = (rand() % 4);
for (j = 0; j < i; j++){
if ((cardRank[i] == cardRank[j]) && (cardSuit[i] == cardSuit[j])){
duplicateCard = 1;
}
}
} while (duplicateCard == 1);
}
}
//below is the getSuit() function that changes the integer value to a character that makes up the suit.
char getSuit(int suit){
switch (suit)
{
case 0:
return ('c');
case 1:
return('d');
case 2:
return('h');
case 3:
return('s');
}
}
//below is the getRank() function that changes the integer value to a character that makes up the rank.
char getRank(int rank) {
switch (rank)
{
case 0:
return ('A');
case 1:
return('2');
case 2:
return('3');
case 3:
return('4');
case 4:
return('5');
case 5:
return('6');
case 6:
return('7');
case 7:
return('8');
case 8:
return('9');
case 9:
return('10');
case 10:
return('J');
case 11:
return('Q');
case 12:
return('K');
}
}
//below is the getBet() function that gets the users bet between 1 and 5 chips
int getBet(){
int bet;
do {
printf("How much do you want to bet? (1 through 5 chips, 0 quits the game..)\n");
scanf(" %d", &bet);
if(bet >=1 && bet <= 5){
return(bet);
}
else if (bet == 0){
exit(1);
}
else{
printf("\n\nPlease enter a bet from 1 through 5 or enter 0 to quit the game.\n");
}
} while((bet < 0) || (bet > 5));
}
//below is the analyzeHand() function that reviews the final hand and figures out the value of the hand.
int analyzeHand(int ranksInHand[], int suitsInHand[]){
int consecNum = 0;
int i, rank, suit;
int straight = FALSE;
int flush = FALSE;
int four = FALSE;
int three = FALSE;
int pairs = 0;
for (suit = 0; suit < 4; suit++){
if(suitsInHand[suit] == 5){
flush = TRUE;
}
}
rank = 0;
while (ranksInHand[rank] == 0){
rank++;
}
for (; rank <13 && ranksInHand[rank]; rank++){
consecNum++;
}
if (consecNum == 5){
straight = TRUE;
}
for (rank = 0; rank < 13; rank++){
if(ranksInHand[rank] == 4){
four = TRUE;
}
if(ranksInHand[rank] == 3){
three = TRUE;
}
if(ranksInHand[rank] == 2){
pairs++;
}
}
if(straight && flush){
printf("You got a straight flush!!!\n\n");
return(20);
} else if (four){
printf("You got four in a row!!\n\n");
return(10);
} else if (three && pairs == 1){
printf("You got a full house!\n\n");
return(8);
} else if (flush){
printf("You got a flush.\n\n");
return(5);
} else if (straight){
printf("You got a straight.\n\n");
return(4);
} else if (three) {
printf("You got three in a row.\n\n");
return(3);
} else if (pairs == 2){
printf("You got two pairs.\n\n");
return(2);
} else if (pairs == 1){
printf("You got a pair.\n\n");
return(1);
} else {
printf("You got a high card. LOL. Because in all reality, you're not playing against anyone. ");
return(0);
}
}
//below is the getFinalHand() function that looks through your 5 cards and asks you if you want to keep the card. If you say no, you get a new card.
void getFinalHand(int cardRank[], int cardSuit[], int finalRank[], int finalSuit[], int ranksInHand[], int suitsInHand[]){
int i, j, duplicateCard;
char suit, rank, ans;
for(i = 0; i < 5; i++){
suit = getSuit(cardSuit[i]);
rank = getRank(cardRank[i]);
printf("Do you want to keep card #%d: %c%c ?", i+1, suit, rank);
printf("\nAnswer Y for Yes and N for No.\n");
scanf(" %c", &ans);
if(toupper(ans) == 'Y'){
finalRank[i] = cardRank[i];
finalSuit[i] = cardSuit[i];
ranksInHand[finalRank[i]]++;
suitsInHand[finalSuit[i]]++;
continue;
} else if (toupper(ans) == 'N'){
duplicateCard = 0;
do{
duplicateCard = 0;
finalRank[i] = (rand() % 13);
finalSuit[i] = (rand() % 4);
for(j= 0; j < 5; j++){
if ((finalRank[i] == cardRank[j]) && (finalSuit[i] == cardSuit[j])){
duplicateCard =1;
}
}
} while(duplicateCard == 1);
ranksInHand[finalRank[i]]++;
suitsInHand[finalSuit[i]]++;
}
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include "Binary_Tree.h"
#include "Aluno.h"
int main(){
Tnode *t = NULL;
int flag = 1;
while(flag){
system("cls");
char opt;
printf(" a: Criar colecao \n b: Inserir tipo \n c: Remover Tipo \n d: Consultar tipo \n e: Listar elementos \n f: Destruir colecao \n g: exit\n");
fflush(stdin);
scanf("%c", &opt);
if(opt == 'a'){
if(t== NULL){
t = abCreate(Aluno_Create());
}
}else if (opt == 'b'){
Aluno *temp = Aluno_Create();
int idade = get_Aluno_idade(temp);
abInsert(t, temp,idade, cmp);
}else if(opt == 'c'){
char nome[20];
int idade;
scanf("%s", &nome);
scanf("%d", &idade);
abRemove(t, nome, idade, cmp);
}else if(opt =='d'){
char nome[20];
int idade;
scanf("%s", &nome);
scanf("%d", &idade);
abSearch(t, nome, idade);
}else if(opt == 'e'){
Simetrica(t);
}else if(opt == 'f'){
t = abDestroy(t);
}else if(opt== 'g'){
flag = 0;
}
system("PAUSE");
}
return 0;
}
|
C
|
#include <lib/string.h>
#include <lib/stdarg.h>
#include <lib/size_t.h>
#include <lib/ctype.h>
/*
Test Usage:
vsprintf("%i", 4); // "4"
vsprintf("%*i", 4, 4); // " 4"
vsprintf("%*i", 4, 12345); // "12345"
vsprintf("%(4)i", 4); // " 4"
vsprintf("%(4)i", 12345); // "12345"
*/
// (Not as in C std lib specification. This is a subset though)
// Formal Grammar rule:
// format: (%(flags)(width)specifier | character)*
/*
flags:
-: Left-justify
+: Force sign
(space): Insert space if no sign
#: Print prefix
0: Left-pad with 0 instead of space
*/
/*
width:
(number): Minimum number of characters to print
*: Minimum number of characters to print as argument before number.
*/
/*
specifier:
c: Character
d | i: Signed dec
o: Signed octal
s: String
u: Unsigned dec
x | X: Unsigned hex
p: Pointer address
%: '%' Character
*/
typedef struct {
uint32_t width;
char specifier;
uint8_t left_justify : 1;
uint8_t force_sign : 1;
uint8_t space : 1;
uint8_t print_prefix : 1;
uint8_t zero_pad : 1;
uint8_t width_as_arg : 1;
uint8_t reserved : 2;
} flags_t;
int is_flag(char c);
int is_specifier(char c);
int parseCommand(const char* format, flags_t* flags, uint32_t* length);
static char _flags[] = "-+ #0";
int is_flag(char c){
for(size_t p = 0; p < strlen(_flags);++p){
if(_flags[p] == c){
return 1;
}
}
return 0;
}
static char _specifiers[] = "cdiosuxXp%";
int is_specifier(char c){
for(size_t p = 0; p < strlen(_specifiers);++p){
if(_specifiers[p] == c){
return 1;
}
}
return 0;
}
int parseCommand(const char* format, flags_t* flags, uint32_t* length){
char* currentChar = format;
// First parse all non-specifier chars
// Check all flags
while(is_flag(*currentChar)){
switch(*currentChar){
case '-':{
flags->left_justify = 1;
break;
}
case '+':{
flags->force_sign = 1;
break;
}
case ' ':{
flags->space = 1;
break;
}
case '#':{
flags->print_prefix = 1;
break;
}
case '0':{
flags->zero_pad = 1;
break;
}
}
// Advance to the next char
++currentChar;
++(*length);
}
// Check width arg(if any)
if(*currentChar == '*'){
flags->width_as_arg = 1;
// Advance to the next char
++currentChar;
++(*length);
} else if (*currentChar == '('){
// Advance
++currentChar;
// Allocate a buffer for the number to be stored
char buf[32] = {0};
size_t i = 0;
while(isdigit(*currentChar)){
buf[i++] = *(currentChar++);
}
// If the next character isn't a ')', the format is wrong. Return error.
if(*currentChar != ')'){
return 1;
}
++currentChar;
buf[i] = '\0'; // Make sure to null terminate
flags->width = atoi(buf);
(*length) += strlen(buf) + 2; // Length of buffer + '(' and ')'
}
// Then get the specifier
if(is_specifier(*currentChar)){
flags->specifier = *currentChar;
++(*length);
return 0;
}
// Specifier is mandatory, return error
return 1;
}
#define output_char(c) (str[loc++] = c)
#define output_string(s) {strcpy(&str[loc], s); \
loc += strlen(s);}
#define PAD(width_delta, pad_char) \
{for(int i_pad = 0; i_pad < width_delta; ++i_pad) \
{ \
output_char(pad_char); \
}}
int vsprintf(char* str, const char* format, va_list ap){
// Sanity check
if(!str)
return 0;
if(!format)
return 0;
// Position in output buffer
size_t loc = 0;
// Position in format string
size_t i = 0;
// Length of the format string
const size_t format_length = strlen(format);
// Loop until all characters in format buffer is parsed
while(i < format_length){
char c = format[i++];
// Check if char is beginning of command
if(c == '%'){
// Initiate flags to 0(No flags are set as default)
flags_t flags;
memset(&flags, 0, sizeof(flags_t));
// The length of the command in format buffer
uint32_t length = 0;
// &format[i] gives the string beginning at the char after '%'
if(parseCommand(&format[i], &flags, &length)){
// We have an error in the format
return 0;
}
// Adjust for command length
i += length;
// Calculate minimum width
int width = 0;
if(flags.width != 0){
width = flags.width;
} else if(flags.width_as_arg){
width = va_arg(ap, int);
}
char pad_char = (flags.zero_pad) ? '0' : ' ';
switch(flags.specifier){
case 'd':
case 'i':{
// Fetch integer from stack
int c = va_arg(ap, int);
// Allocate a small buffer
char s[32] = {0};
// Convert int to string
itoa_s(c, 10, s);
// Calculate pad length
int width_delta = width - strlen(s);
// If int is pos or 0
if(c >= 0){
// Manually insert '+' if positive
if(flags.force_sign){
output_char('+');
width_delta -= 1;
// Insert ' ' so positive values will line up with
// negative values
} else if(flags.space){
output_char(' ');
width_delta -= 1;
}
}
if(flags.left_justify){
output_string(s);
PAD(width_delta, pad_char);
} else {
PAD(width_delta, pad_char);
output_string(s);
}
break;
}
case 'o':{
// Fetch integer from stack
int c = va_arg(ap, int);
// Allocate a small buffer
char s[32] = {0};
// Convert int to string
itoa_s(c, 8, s);
// Calculate pad length
int width_delta = width - strlen(s);
// If int is pos or 0
if(c >= 0){
// Manually insert '+' if positive
if(flags.force_sign){
output_char('+');
width_delta -= 1;
// Insert ' ' so positive values will line up with
// negative values
} else if(flags.space){
output_char(' ');
width_delta -= 1;
}
}
if(flags.print_prefix){
output_string("0");
width_delta -= 1;
}
if(flags.left_justify){
output_string(s);
PAD(width_delta, pad_char);
} else {
PAD(width_delta, pad_char);
output_string(s);
}
break;
}
case 's':{
// Fetch string pointer from stack
char* c = (char*) va_arg(ap, char*);
// Allocate a small buffer
// TODO: Increase if needed
char s[32]={0};
// Copy string to buffer
strcpy(s, (const char*)c);
// Calculate pad length
int width_delta = width - strlen(s);
if(flags.left_justify){
output_string(s);
PAD(width_delta, pad_char);
} else {
PAD(width_delta, pad_char);
output_string(s);
}
break;
}
case 'u':{
// Fetch integer from stack
unsigned int c = va_arg(ap, unsigned int);
// Allocate a small buffer
char s[32] = {0};
// Convert int to string
itoa(c, 10, s);
// Calculate pad length
int width_delta = width - strlen(s);
if(flags.left_justify){
output_string(s);
PAD(width_delta, pad_char);
} else {
PAD(width_delta, pad_char);
output_string(s);
}
break;
}
case 'p': // A minor hack
case 'x':
case 'X':{
// Fetch integer from stack
unsigned int c = va_arg(ap, unsigned int);
// Allocate a small buffer
char s[32] = {0};
itoa(c, 16, s);
// Calculate pad length
int width_delta = width - strlen(s);
if(flags.print_prefix){
output_string("0x");
width_delta -= 2;
}
if(flags.left_justify){
output_string(s);
PAD(width_delta, pad_char);
} else {
PAD(width_delta, pad_char);
output_string(s);
}
break;
}
case 'c':{
char c = va_arg(ap, char);
int width_delta = width - 1;
if(flags.left_justify){
output_char(c);
PAD(width_delta, pad_char);
} else {
PAD(width_delta, pad_char);
output_char(c);
}
break;
}
case '%':{
int width_delta = width - 1;
if(flags.left_justify){
output_char('%');
PAD(width_delta, pad_char);
} else {
PAD(width_delta, pad_char);
output_char('%');
}
break;
}
}
} else {
output_char(c);
}
}
}
|
C
|
#include "../include/lsb1.h"
static void hide_bit(unsigned char *buffer, int size, unsigned char data_bit);
static unsigned char lsb(unsigned char * buffer, int buffer_bytes);
void hide_lsb1(FILE * vector, FILE * orig_file, unsigned short int sample_bytes, char * data,
unsigned int bytes_to_hide) { // TODO: unsigned long
int input_bytes_read = 0;
int bits_hidden = 0;
unsigned char bit_to_hide;
unsigned char * buffer = (unsigned char *) calloc(1, sizeof(char));
//leo un sample a la vez
while ((input_bytes_read = fread(buffer, BYTE_SIZE, sample_bytes, orig_file)) > 0) {
if (bits_hidden >= BITS_PER_BYTE) { //si ya lei todo un byte agarro el que sigue
bits_hidden = 0;
bytes_to_hide--;
data++;
}
if (bytes_to_hide > 0) {
// agarro el bit mas significativo
bit_to_hide = ((*data) >> (7 - bits_hidden)) & 0x01;
// cambio el ultimo bit del buffer de lectura
hide_bit(buffer, sample_bytes, bit_to_hide);
bits_hidden++;
}
fwrite(buffer, BYTE_SIZE, input_bytes_read, vector); // Writing read data into output file
}
if(bytes_to_hide > 0){
printf("NO TERMINO DE HIDEAR TODO!\n");
exit(1);
}
}
void hide_bit(unsigned char * buffer, int buffer_size, unsigned char data_bit) {
int last_idx = buffer_size - 1;
buffer[last_idx] = (buffer[last_idx] & ~0x01) | data_bit;
}
int recover_lsb1(char * out_path, FILE * vector, unsigned short int sample_bytes, bool ext) {
// load body size
DWORD data_size = 0;
recover_bytes_lsb1((char *) &data_size, vector, sample_bytes, sizeof(DWORD));
data_size = __builtin_bswap32(data_size);
char * data = (char *) calloc(data_size, sizeof(char));
recover_bytes_lsb1(data, vector, sample_bytes, data_size);
char extension[MAX_EXT_LEN + 1] = { '\0' };
if (ext) {
int i = 0;
char ext_c = 0;
do {
recover_bytes_lsb1(&ext_c, vector, sample_bytes, sizeof(char));
extension[i] = ext_c;
i++;
} while (ext_c != '\0');
}
// save all to new file
int bytes_recovered = create_file(out_path, extension, data, data_size);
free(data);
return bytes_recovered;
}
int recover_bytes_lsb1(char * data, FILE * vector, unsigned short int sample_bytes, unsigned int bytes_to_read) {
unsigned char * vector_buffer = (unsigned char *) calloc(sample_bytes, BYTE_SIZE);
unsigned char data_byte = 0;
unsigned int bytes_read = 0;
unsigned int bits_read = 0;
while (bytes_read < bytes_to_read) {
fread(vector_buffer, 1, sample_bytes, vector); // TODO: == -1 ?
data_byte <<= 1;
data_byte |= lsb(vector_buffer, sample_bytes);
bits_read++;
if (bits_read == BITS_PER_BYTE) { //si ya lei todo un byte agarro el que sigue
data[bytes_read] = data_byte;
data_byte = 0;
bits_read = 0;
bytes_read++;
}
}
free(vector_buffer);
return bytes_to_read;
}
unsigned char lsb(unsigned char * buffer, int buffer_bytes) {
return (buffer[buffer_bytes - 1]) & 0x01;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Declaracion de variables
int x;
// Obtenemos el valor de la variable
printf("Ingresa el valor de x: ");
scanf("%i", &x);
// Caculamos x % 5
x %= 5;
// Mostramos el resultado mas uno de incremento
printf("El valor final de x es: %i", ++x);
return 0;
}
|
C
|
/*************************************************************************
> File Name: p1.c
> Author:
> Mail:
> Created Time: Wed 11 Dec 2019 11:15:26 AM UTC
************************************************************************/
#include<stdio.h>
#define HOUR_MIN 60
int main(void)
{
int min, hours, mins;
printf("Please enter the time in seconds:\n");
scanf("%d", &min);
while (min > 0)
{
hours = min / HOUR_MIN;
mins = min % HOUR_MIN;
printf("You spend %d minutes, means spending %d hours, %d minutes\n", min, hours, mins);
printf("please enter another time :\n");
scanf("%d", &min);
}
printf("Done!\n");
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main(int argc,char *argv[]) //command line argument
{
int a,b;
if(argc!=3) //checks if entered number is greater than 2
{
printf("\nenter only two values");
exit(1);
}
else
{
a=atoi(argv[1]);
b=atoi(argv[2]);
{
if(a>b)
printf("\n%d is greatest",a);
else
printf("\n%d is greatest",b);
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int* merge_array(int*a, int a_size ,int* b, int b_size)
{
int i=0, j=0;
int *c = malloc((a_size+b_size)*sizeof(int));
a[a_size-1] = INT_MAX;
b[b_size-1] = INT_MAX;
while((i+j)<=a_size+b_size)
{
if( a[i]<b[j])
{
c[i+j]=a[i];
i++;
}else
{
c[i+j]=b[j];
j++;
}
}
return c;
}
int* merge_sort(int *array, int ini, int end)
{
int* a, *b;
if(end-ini == 1)
return array;
*a = merge_sort(array, ini, (end-ini)/2);
*b = merge_sort(array, ((end-ini)/2)+1, end);
return merge_array(a, ((end-ini)/2)-ini, b, end - ((end-ini)/2)+1);
}
int main()
{
int a[7] = {4,5,8,9,30,31},
// b[9] = {2, 6, 8,10,22,32,100, 102},
b[9] = {5, 10,1, 0, 56, 7, 58, 23, 14},
*c, i;
c = merge_sort(&b, 0, 8);
//merge_array(a, )
for(i=0; i<9; i++)
{
printf("%d ", c[i]);
}
return 1;
}
|
C
|
Given a sorted list of words, find the longest compound word in the list that is
constructed by concatenating the words in the list. For example, if the input
list is: ['cat', 'cats', 'catsdogcats', 'catxdogcatsrat', 'dog', 'dogcatsdog',
'hippopotamuses', 'rat', 'ratcat', 'ratcatdog', 'ratcatdogcat']. Then the
longest compound word is ‘ratcatdogcat’ with 12 letters. Note that the longest
individual words are ‘catxdogcatsrat’ and ‘hippopotamuses’ with 14 letters, but
they’re not fully constructed by other words. Former one has an extra ‘x’
letter, and latter is an individual word by itself not a compound word.
|
C
|
/* GStreamer Language Tag Utility Functions
* Copyright (C) 2009 Tim-Philipp Müller <tim centricular net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
/* mklangtables.c:
* little program that reads iso_639.xml and outputs tables for us as fallback
* for when iso-codes are not available or we fail to read the file for some
* reason, and so we don't have to parse the xml file just to map codes.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <glib.h>
#include <string.h>
#define ISO_639_XML_PATH ISO_CODES_PREFIX "/share/xml/iso-codes/iso_639.xml"
typedef struct
{
gchar code_1[3]; /* de */
gchar code_2t[4]; /* deu */
gchar code_2b[4]; /* ger */
const gchar *name; /* German */
guint name_offset; /* offset into string table */
} IsoLang;
static GArray *languages = NULL;
static void
dump_languages (void)
{
GString *names;
const char *s;
int i, num_escaped;
g_assert (languages != NULL);
names = g_string_new ("");
g_print ("/* generated by mklangtables from iso-codes " ISO_CODES_VERSION
" */\n");
g_print ("/* License: LGPL-2.1+ */\n");
g_print ("\n");
g_print ("#include <glib.h>\n");
g_print ("\n");
g_print ("#define ISO_639_FLAG_2T (1 << 0)\n");
g_print ("#define ISO_639_FLAG_2B (1 << 1)\n");
g_print ("\n");
g_print ("/* *INDENT-OFF* */\n");
g_print ("\n");
g_print ("static const struct\n");
g_print ("{\n");
g_print (" const gchar iso_639_1[3];\n");
g_print (" const gchar iso_639_2[4];\n");
g_print (" guint8 flags;\n");
g_print (" guint16 name_offset;\n");
g_print ("} iso_639_codes[] = {\n");
for (i = 0, num_escaped = 0; i < languages->len; ++i) {
IsoLang *lang = &g_array_index (languages, IsoLang, i);
/* For now just print those where there's both a ISO-639-1 and -2 code */
if (lang->code_1[0] == '\0')
continue;
/* save current offset */
lang->name_offset = names->len;
/* adjust for fact that \000 is 4 chars now but will take up only 1 later */
lang->name_offset -= num_escaped * 3;
/* append one char at a time, making sure to escape UTF-8 characters */
for (s = lang->name; s != NULL && *s != '\0'; ++s) {
if (g_ascii_isprint (*s) && *s != '"' && *s != '\\') {
g_string_append_c (names, *s);
} else {
g_string_append_printf (names, "\\%03o", (unsigned char) *s);
++num_escaped;
}
}
g_string_append (names, "\\000");
++num_escaped;
g_print (" /* %s */\n", lang->name);
if (strcmp (lang->code_2b, lang->code_2t) == 0) {
g_print (" { \"%s\", \"%s\", ISO_639_FLAG_2T | ISO_639_FLAG_2B, %u },\n",
lang->code_1, lang->code_2t, lang->name_offset);
} else {
/* if 639-2T and 639-2B differ, put 639-2T first */
g_print (" { \"%s\", \"%s\", ISO_639_FLAG_2T, %u },\n",
lang->code_1, lang->code_2t, lang->name_offset);
g_print (" { \"%s\", \"%s\", ISO_639_FLAG_2B, %u },\n",
lang->code_1, lang->code_2b, lang->name_offset);
}
}
g_print ("};\n");
g_print ("\n");
g_print ("static const gchar iso_639_names[] =\n");
s = names->str;
while (s != NULL && *s != '\0') {
gchar line[74], *lastesc;
guint left;
left = strlen (s);
g_strlcpy (line, s, MIN (left, sizeof (line)));
s += sizeof (line) - 1;
/* avoid partial escaped codes at the end of a line */
if ((lastesc = strrchr (line, '\\')) && strlen (lastesc) < 4) {
s -= strlen (lastesc);
*lastesc = '\0';
}
g_print (" \"%s\"", line);
if (left < 74)
break;
g_print ("\n");
}
g_print (";\n");
g_print ("\n");
g_print ("/* *INDENT-ON* */\n");
g_string_free (names, TRUE);
}
static gboolean
copy_attribute (gchar * dest, guint dest_len, const gchar ** attr_names,
const gchar ** attr_vals, const gchar * needle)
{
while (attr_names != NULL && *attr_names != NULL) {
if (strcmp (*attr_names, needle) == 0) {
g_strlcpy (dest, *attr_vals, dest_len);
return TRUE;
}
++attr_names;
++attr_vals;
}
dest[0] = '\0';
return FALSE;
}
static void
xml_start_element (GMarkupParseContext * ctx, const gchar * element_name,
const gchar ** attr_names, const gchar ** attr_vals,
gpointer user_data, GError ** error)
{
gchar name[256];
IsoLang lang;
if (strcmp (element_name, "iso_639_entry") != 0)
return;
copy_attribute (lang.code_1, 3, attr_names, attr_vals, "iso_639_1_code");
copy_attribute (lang.code_2t, 4, attr_names, attr_vals, "iso_639_2T_code");
copy_attribute (lang.code_2b, 4, attr_names, attr_vals, "iso_639_2B_code");
copy_attribute (name, sizeof (name), attr_names, attr_vals, "name");
lang.name = g_intern_string (name);
g_array_append_val (languages, lang);
}
static void
parse_iso_639_xml (const gchar * data, gsize len)
{
GMarkupParser xml_parser = { xml_start_element, NULL, NULL, NULL, NULL };
GMarkupParseContext *ctx;
GError *err = NULL;
g_return_if_fail (g_utf8_validate (data, len, NULL));
ctx = g_markup_parse_context_new (&xml_parser, 0, NULL, NULL);
if (!g_markup_parse_context_parse (ctx, data, len, &err))
g_error ("Parsing failed: %s", err->message);
g_markup_parse_context_free (ctx);
}
static gint
languages_sort_func (IsoLang * l1, IsoLang * l2)
{
if (l1 == l2)
return 0;
if (l1->code_1[0] == '\0' && l2->code_1[0] != '\0')
return -1;
return strcmp (l1->code_1, l2->code_1);
}
int
main (int argc, char **argv)
{
GMappedFile *f;
gchar *xml_data;
gsize xml_len;
f = g_mapped_file_new (ISO_639_XML_PATH, FALSE, NULL);
if (f != NULL) {
xml_data = (gchar *) g_mapped_file_get_contents (f);
xml_len = g_mapped_file_get_length (f);
} else {
GError *err = NULL;
if (!g_file_get_contents (ISO_639_XML_PATH, &xml_data, &xml_len, &err))
g_error ("Could not read %s: %s", ISO_639_XML_PATH, err->message);
}
languages = g_array_new (FALSE, TRUE, sizeof (IsoLang));
parse_iso_639_xml (xml_data, xml_len);
g_array_sort (languages, (GCompareFunc) languages_sort_func);
dump_languages ();
g_array_free (languages, TRUE);
if (f != NULL)
g_mapped_file_unref (f);
else
g_free (xml_data);
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
int eh_primo_i(int i, int x)
{
if(x == 2) return 1;
if (i > sqrt(x))
{
return 1;
}
if (x % i == 0)
{
return 0;
}
return eh_primo_i(i + 1, x);
}
int eh_primo(int x)
{
return eh_primo_i(2, x);
}
int prova()
{
int n1;
scanf("%d",&n1);
if(eh_primo(n1)) printf("É primo\n");
else printf("Não é primo\n");
}
int main()
{
prova();
return 0;
}
|
C
|
#include <stdio.h>
int main(void){
// 出力
printf("Hello word\n");
puts("putsは何もしなくても改行してくれる");
printf("printf はバックスラッシュn を入れないと改行されない\n");
// 入力
int a;
a = 10;
printf("%d\n", a + 1);
int num;
scanf("%d", &num); // bの中に user から入力された値を入れる
// ここで一度実行が stop
// 値が入力されたら実行される
printf("あなたの入力した値は %d ですね\n", num); // 入力値を表示
return 0;
}
|
C
|
/*
Challenge 204
Task 2: Reshape Matrix
Submitted by: Mohammad S Anwar
You are given a matrix (m x n) and two integers (r) and (c).
Write a script to reshape the given matrix in form (r x c) with the original value in the given matrix. If you can’t reshape print 0.
Example 1
Input: [ 1 2 ]
[ 3 4 ]
$matrix = [ [ 1, 2 ], [ 3, 4 ] ]
$r = 1
$c = 4
Output: [ 1 2 3 4 ]
Example 2
Input: [ 1 2 3 ]
[ 4 5 6 ]
$matrix = [ [ 1, 2, 3 ] , [ 4, 5, 6 ] ]
$r = 3
$c = 2
Output: [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ]
[ 1 2 ]
[ 3 4 ]
[ 5 6 ]
Example 3
Input: [ 1 2 ]
$matrix = [ [ 1, 2 ] ]
$r = 3
$c = 2
Output: 0
*/
#define MAX_DATA 1024
#define BLANKS " \t\r\n\v\f"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int data[MAX_DATA], size = 0, rows = 0, cols = 0;
void parse_data() {
char line[MAX_DATA], *p;
while (fgets(line, sizeof(line), stdin)) {
if (strchr(line, '[') != NULL) {
while ((p = strchr(line, '[')) != NULL) *p = ' ';
while ((p = strchr(line, ']')) != NULL) *p = ' ';
char* p = strtok(line, BLANKS);
while (p) {
assert(size < MAX_DATA);
data[size++] = atoi(p);
p = strtok(NULL, BLANKS);
}
}
else {
char* p = strtok(line, BLANKS);
assert(p);
rows = atoi(p);
p = strtok(NULL, BLANKS);
assert(p);
cols = atoi(p);
break;
}
}
}
void output_data() {
if (size != rows*cols)
printf("0\n");
else {
for (int i = 0; i < rows; i++) {
printf("[ ");
for (int j = 0; j < cols; j++) {
printf("%d ", data[i*cols+j]);
}
printf("]\n");
}
}
}
int main() {
parse_data();
output_data();
}
|
C
|
#include "dominion.h"
#include "dominion_helpers.h"
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include "rngs.h"
// set NOISY_TEST to 0 to remove printfs from output
#define NOISY_TEST 1
int main() {
int i, j, c;
int seed = 1000;
int numPlayers = 4;
int r;
int k[10] = {adventurer, council_room, feast, gardens, mine
, remodel, smithy, village, baron, great_hall};
struct gameState G;
for (i = 2; i <= numPlayers; ++i)
{
memset(&G, 23, sizeof G);
r = initializeGame(i, k, seed, &G);
printf("Test for whoseTurn() with %d players:\n", i);
for (j = 0; j < i; ++j)
{
c = whoseTurn(&G);
assert(c == j);
printf("On player %d's turn, whoseTurn() returns player %d.\n", j, j);
endTurn(&G);
}
}
printf("All tests passed!\n");
return 0;
}
|
C
|
#include "Common.h"
#include "Genotypes.h"
#include "TaskMacros.h"
#include "TableProc.h"
#include "Sort.h"
// Move pointer to the appropriate row/SNP position (new_index) in .bed file
/*
void bed_set_row(struct pio_file_t *plink_file, size_t new_index)
{
size_t offset = bed_header_data_offset(&(&plink_file->bed_file)->header) + (new_index - 1)*ceil(pio_num_samples(plink_file) / 4);
fseek((&plink_file->bed_file)->fp, offset, SEEK_SET);
(&plink_file->bed_file)->cur_row = new_index;
}
vector<vector<unsigned short>> InputPLINK::createGenotypeMatrix(int lowInd, int upInd) {
if (lowInd < 0) lowInd = 0;
if (upInd < 0) upInd = 0;
vector<vector<unsigned short>> result;
struct pio_file_t plink_file; // Opens all three files at once (.bed, .bim, .fam)
snp_t *snp_buffer;
if (pio_open(&plink_file, this->filename) != PIO_OK) {
cout << "Error here: Could not open " << this->filename << endl;
}
if (!pio_one_locus_per_row(&plink_file)) {
cout << "This script requires that snps are rows and samples columns." << endl;
}
snp_buffer = (snp_t *) malloc(pio_row_size(&plink_file));
vector<unsigned short> snp_row;
bed_set_row(&plink_file, lowInd); // Set the first SNP id we want to read
int num_snps = 0; // Make sure we read the right amount of SNPs
// Loop reads the interval [lowInd,upInd] (numeration starts at zero!) from genotype (.bed file)
while (pio_next_row(&plink_file, snp_buffer) == PIO_OK && num_snps < upInd - lowInd + 1) {
snp_row = {};
for (int sample_id = 0; sample_id < pio_num_samples(&plink_file); sample_id++) {
snp_row.push_back((unsigned short) snp_buffer[sample_id]);
}
result.push_back(snp_row);
num_snps++;
}
free(snp_buffer);
pio_close(&plink_file);
return result;
}
vector<unsigned short> InputPLINK::createPhenotypeVector() {
string fam_file_name(this->filename);
fam_file_name += ".fam";
vector<unsigned short> result;
char delim = ' ';
string fam_line_word;
ifstream handle(fam_file_name);
string fam_line;
int ind;
while (getline(handle, fam_line))
{
stringstream ss;
ss.str(fam_line);
ind = 0;
while (getline(ss, fam_line_word, delim)) {
ind++;
if (ind == 6) {
result.push_back((unsigned short) stoi(fam_line_word));
}
}
}
handle.close();
return result;
}
*/
enum chr {
CHR_UNDEFINED = 0,
CHR_X = 23,
CHR_Y = 24
};
bool chrHandler(const char *str, size_t len, uint16_t *ptr, handlerContext *context)
{
(void) len;
char *test;
*ptr = (uint16_t) strtoul(str, &test, 10);
if (*test)
{
if (!strcmpci(str, "X")) *ptr = 23;
else if (!strcmpci(str, "Y")) *ptr = 24;
else return 0;
}
if (context) bitSet((unsigned char *) ptr + context->set, context->pos);
return 1;
}
static const tblsch statSchBim = CLII((tblcolsch[])
{
{ .handler = { .read = (readHandlerCallback) chrHandler }, .ind = 0, .size = sizeof(uint16_t) }, // genotypesRes::chr_len
{ .handler = { .read = (readHandlerCallback) strTableHandler }, .ind = 1, .size = sizeof(ptrdiff_t) }, // genotypesRes::snpname
{ .handler = { .read = NULL } }, // dinstance in Morgans
{ .handler = { .read = (readHandlerCallback) uint32Handler }, .ind = 2, .size = sizeof(uint32_t) }, // genotypesRes::pos
{ .handler = { .read = NULL } }, // allele Major
{ .handler = { .read = NULL } } // allele Minor
});
bool read_bim(genotypesRes *res, genotypesContext *context)
{
FILE *f = fopen(context->path_bim, "rb");
// if (!f) ...
fseek64(f, 0, SEEK_END);
size_t sz = ftell64(f);
size_t row_cnt = rowCount(f, 0, sz);
void *tbl[3];
tblInit((void **) &tbl, (tblsch *) &statSchBim, row_cnt, 1);
char *str = NULL;
size_t strtblcnt = 0, strtblcap = 0;
void *cont[] = { [1] = &(strTableHandlerContext) { .strtbl = &str, .strtblcnt = &strtblcnt, .strtblcap = &strtblcap }, [4] = NULL };
fseek64(f, 0, SEEK_SET);
rowRead(f, (tblsch *) &statSchBim, tbl, cont, 0, 0, 0, NULL, '\t');
uint8_t chr_bits[BYTE_CNT(25)] = { 0 };
for (size_t i = 0; i < row_cnt; i++)
{
uint16_t ind = ((uint16_t *) (tbl[0]))[i];
if (ind < 25) bitSet(chr_bits, ind);
}
size_t chr_cnt = 25;
for (size_t i = 25; i; i--) if (!bitTest(chr_bits, i - 1)) chr_cnt--;
res->snp_cnt = row_cnt;
res->chr_cnt = chr_cnt;
res->chr_len = calloc(chr_cnt, sizeof(*res->chr_len));
for (size_t i = 0; i < row_cnt; i++)
{
uint16_t ind = ((uint16_t *) (tbl[0]))[i];
if (ind < chr_cnt) res->chr_len[ind]++;
}
res->pos = tbl[2];
res->snp_name_off = tbl[1];
res->snp_name = str;
res->snp_name_sz = strtblcnt;
free(tbl[0]);
fclose(f);
return 1;
}
static const tblsch statSchFam = CLII((tblcolsch[])
{
{ .handler = { .read = NULL } },
{ .handler = { .read = NULL } },
{ .handler = { .read = NULL } },
{ .handler = { .read = NULL } },
{ .handler = { .read = NULL } },
{ .handler = { .read = (readHandlerCallback) strTableHandler }, .ind = 0, .size = sizeof(ptrdiff_t) } // phenotype
});
int8_t uint16Comp(const uint16_t *a, const uint16_t *b, void *context)
{
(void) context;
return *a > *b ? 1 : *a == *b ? 0 : -1;
}
bool read_fam(genotypesRes *res, genotypesContext *context)
{
FILE *f = fopen(context->path_fam, "rb");
// if (!f) ...
fseek64(f, 0, SEEK_END);
size_t sz = ftell64(f);
size_t row_cnt = rowCount(f, 0, sz);
void *tbl[1];
tblInit((void **) &tbl, (tblsch *) &statSchFam, row_cnt, 1);
char *str = NULL;
size_t strtblcnt = 0, strtblcap = 0;
void *cont[6] = { [0] = &(strTableHandlerContext) { .strtbl = &str, .strtblcnt = &strtblcnt, .strtblcap = &strtblcap } };
fseek64(f, 0, SEEK_SET);
bool r = rowRead(f, (tblsch *) &statSchFam, tbl, cont, 0, 0, 0, NULL, ' ');
res->phn_off = tbl[0];
res->phn_cnt = row_cnt;
res->phn_name = str;
res->phn_name_sz = strtblcnt;
//ordersStableUnique(tbl[0], row_cnt, sizeof(uint16_t), uint16Comp, NULL, &res->phn_uni);
return 1;
}
union gen {
uint8_t bin;
struct {
uint8_t n0 : 2;
uint8_t n1 : 2;
uint8_t n2 : 2;
uint8_t n3 : 2;
};
};
bool read_bed(genotypesRes *res, genotypesContext *context)
{
char remap[] = { 0, 3, 1, 2 };
FILE *f = fopen(context->path_bed, "rb");
char buff[BLOCK_READ];
size_t snp_ind = 0, phn_ind = 0;;
size_t rd = fread(buff, sizeof(*buff), countof(buff), f), pos = 0;
if (strncmp(buff, "\x6c\x1b\x01", 3)) return 0;
pos = 3;
res->gen = malloc(res->snp_cnt * (res->phn_cnt + 3) / 4);
for (; rd; rd = fread(buff, sizeof(*buff), countof(buff), f), pos = 0)
{
for (size_t i = pos; i < rd; i++)
{
union gen gen_in = { .bin = buff[i] }, gen_out = { .n0 = remap[gen_in.n0], .n1 = remap[gen_in.n1], .n2 = remap[gen_in.n2], .n3 = remap[gen_in.n3] };
res->gen[res->snp_cnt * (res->phn_cnt + 3) / 4 + phn_ind / 4] = gen_out.bin;
phn_ind += 4;
if (phn_ind >= res->phn_cnt) phn_ind = 0, snp_ind++;
if (snp_ind == res->snp_cnt) return 0; // error msg
}
}
return 1;
}
static void genotypesResClose(genotypesRes *res)
{
free(res->gen);
}
static bool genotypesThreadProc(loopMTArg *args, genotypesThreadProcContext *context)
{
FILE *f = fopen(context->context->path_bed, "rb");
if (!f) goto ERR();
if (!fseek64(f, args->offset, SEEK_SET) && fread(context->out->res.gen + args->offset, 1, args->length, f) == args->length)
{
logMsg(FRAMEWORK_META(context->out)->log, "INFO (%s): Thread %zu have read %zu bytes of the file %s + %zu B.\n", __FUNCTION__, threadPoolFetchThredId(FRAMEWORK_META(context->out)->pool), args->length, context->context->path_bed, args->offset);
}
else
{
logMsg(FRAMEWORK_META(context->out)->log, "ERROR (%s): Thread %zu cannot read the file %s + %zu B!\n", __FUNCTION__, threadPoolFetchThredId(FRAMEWORK_META(context->out)->pool), context->context->path_bed, args->offset);
fclose(f);
return 0;
}
fclose(f);
return 1;
ERR() :
logError(FRAMEWORK_META(context->out)->log, __FUNCTION__, errno);
return 0;
}
static bool genotypesThreadPrologue(genotypesOut *args, genotypesContext *context)
{
const char *strings[] =
{
__FUNCTION__,
"ERROR (%s): Cannot open specified file \"%s\". %s!\n",
"ERROR (%s): Unable to setup parallel loop!\n"
};
enum { STR_FN, STR_FR_EI, STR_FR_LP };
read_bim(&args->res, context);
read_fam(&args->res, context);
read_bed(&args->res, context);
/*
char tempbuff[TEMP_BUFF] = { '\0' };
FILE *f = NULL;
f = fopen(context->path_bed, "rb");
if (!f) goto ERR(File);
fseek64(f, 0, SEEK_END);
size_t sz = ftell64(f);
args->supp.sync = (loopMTSync) {
.asucc = (aggregatorCallback) bitSet2InterlockedMem,
.afail = (aggregatorCallback) bitSetInterlockedMem,
.asuccmem = args->supp.stat,
.afailmem = args->supp.stat,
.asuccarg = pnumGet(FRAMEWORK_META(args)->pnum, GENOTYPES_STAT_BIT_POS_TASK_COMP),
.afailarg = pnumGet(FRAMEWORK_META(args)->pnum, GENOTYPES_STAT_BIT_POS_TASK_COMP),
};
args->supp.context = (genotypesThreadProcContext) { .out = args, .context = context };
args->res.gen_cnt = sz;
args->res.gen = malloc(sz);
if (sz && !args->res.gen) goto ERR();
args->supp.lmt = loopMTCreate((loopMTCallback) genotypesThreadProc, 0, sz, &args->supp.context, FRAMEWORK_META(args)->pool, &args->supp.sync);
if (!args->supp.lmt) goto ERR(Loop);
fclose(f);
*/
for (;;)
{
return 1;
ERR():
logError(FRAMEWORK_META(args)->log, __FUNCTION__, errno);
break;
ERR(File):
//strerror_s(tempbuff, sizeof tempbuff, errno);
//logMsg(FRAMEWORK_META(args)->log, strings[STR_FR_EI], strings[STR_FN], context->path_bed, tempbuff);
break;
ERR(Loop):
logMsg(FRAMEWORK_META(args)->log, strings[STR_FR_LP], strings[STR_FN]);
break;
}
//if (f) fclose(f);
return 0;
}
void genotypesContextDispose(genotypesContext *context)
{
if (!context) return;
free(context->path_bim);
free(context->path_fam);
free(context->path_bed);
free(context);
}
bool genotypesPrologue(genotypesIn *in, genotypesOut **pout, genotypesContext *context)
{
genotypesOut *out = *pout = malloc(sizeof *out);
if (!out) goto ERR();
*out = (genotypesOut) { .meta = GENOTYPES_META_INIT(in, out, context) };
if (!outInfoSetNext(FRAMEWORK_META(in)->out, out)) goto ERR();
task *tsk = tasksInfoNextTask(FRAMEWORK_META(in)->tasks);
if (!tsk) goto ERR();
if (!pnumTest(FRAMEWORK_META(out)->pnum, GENOTYPES_STAT_BIT_CNT)) goto ERR();
*tsk = TASK_BIT_1_INIT(genotypesThreadPrologue, NULL, out, context, NULL, out->supp.stat, pnumGet(FRAMEWORK_META(out)->pnum, GENOTYPES_STAT_BIT_POS_INIT_COMP));
return 1;
ERR() :
logError(FRAMEWORK_META(in)->log, __FUNCTION__, errno);
return 0;
}
static bool genotypesThreadClose(genotypesOut *args, void *context)
{
(void) context;
if (!args) return 1;
genotypesResClose(&args->res);
loopMTDispose(args->supp.lmt);
return 1;
}
static bool genotypesThreadCloseCondition(genotypesSupp *supp, void *arg)
{
(void) arg;
switch (bitGet2((void *) supp->stat, GENOTYPES_STAT_BIT_POS_INIT_COMP))
{
case 0: return 0;
case 1: return 1;
case 3: break;
}
switch (bitGet2((void *) supp->stat, GENOTYPES_STAT_BIT_POS_TASK_COMP))
{
case 0: return 0;
case 1: return 1;
case 3: break;
}
return !(supp->hold);
}
bool genotypesEpilogue(genotypesIn *in, genotypesOut* out, void *context)
{
if (!out) return 0;
(void) context;
task *tsk = tasksInfoNextTask(FRAMEWORK_META(in)->tasks);
if (!tsk) goto ERR();
*tsk = (task)
{
.arg = out,
.callback = (taskCallback) genotypesThreadClose,
.cond = (conditionCallback) genotypesThreadCloseCondition,
.condmem = &out->supp
};
return 1;
ERR():
logError(FRAMEWORK_META(in)->log, __FUNCTION__, errno);
return 0;
}
|
C
|
#include <iostream>
using std::cout; using std::cin; using std::endl; using std::string;
int main()
{
string input = "teststring";
for (char &c : input)
c = 'X';
cout << input << endl;
}
|
C
|
int main(){
int n;
printf("Enter the number of terms\n");
scanf("%d",&n);
printf("Enter the %d terms\n",n);
int a[n];
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
selectsort(a,n);
printf("After sorting\n");
for(int i=0;i<n;i++){
printf("%d\n",a[i]);
}
}
|
C
|
/*
* Puella Ardens - Burning Man GirlTech based IM communicator.
*/
#include <cc1110.h>
#include <stdio.h>
#include <string.h>
#include "display.h"
#include "inbox_view.h"
#include "keys.h"
#include "message.h"
#define ADD_TEST_MSG(_i, _msg, _attr) \
strcpy(msg_buffer_[_i].text, _msg); \
msg_buffer_[_i].attr = _attr; \
/* File global variables. */
static __xdata MessageInfo msg_buffer_[NUM_MESSAGES];
static uint8_t cur_msg_;
static uint8_t first_msg_;
static uint8_t last_msg_;
/* Internal functions. */
uint8_t draw_message(const MessageInfo* msg, uint8_t row) {
uint8_t msg_len = strlen(msg->text);
uint8_t msg_pos = 0;
uint8_t col = 0;
bit last_row = 0;
char start_char = '>';
SSN = LOW;
setDisplayStart(0);
/* Render the first row, which is 2 short for indicators. */
if (msg_len <= CHAR_WIDTH - 2) {
last_row = 1;
}
setCursor(row, 0);
if (msg->attr & MSG_ATTR_MINE) {
start_char = '$';
}
if (last_row) {
putchar_mask(start_char, 0x80);
} else {
putchar(start_char);
}
for (col = 1; col < CHAR_WIDTH - 1 && msg_pos < msg_len; ++col, ++msg_pos) {
if (last_row) {
putchar_mask(msg->text[msg_pos], 0x80);
} else {
putchar(msg->text[msg_pos]);
}
}
if (last_row) {
for (col; col < CHAR_WIDTH - 1; ++col) {
putchar_mask(' ', 0x80);
}
}
++row;
/* Render any message indicators. */
txData(0xFF);
txData(0x80);
if (msg->attr & MSG_ATTR_MINE) {
if (msg->attr & MSG_ATTR_SENT) {
putchar_mask('M', 0x80);
} else {
putchar_mask('?', 0x80);
}
} else {
if (msg->attr & MSG_ATTR_NEW) {
putchar_mask('*', 0x80);
} else {
putchar_mask(' ', 0x80);
}
}
/* Render the remaining rows of the message */
while (row < CHAR_HEIGHT && msg_pos < msg_len) {
if (msg_pos >= msg_len - CHAR_WIDTH) {
last_row = 1;
}
/* Draw the text on this row. */
setCursor(row, 0);
for (col = 0; col < CHAR_WIDTH && msg_pos < msg_len; ++col, ++msg_pos) {
if (last_row) {
putchar_mask(msg->text[msg_pos], 0x80);
} else {
putchar(msg->text[msg_pos]);
}
}
/* Finish drawing the line on the last row. */
if (last_row) {
for (col; col < CHAR_WIDTH; ++col) {
putchar_mask(' ', 0x80);
}
txData(0x80);
txData(0x80);
}
++row;
}
/* For debugging, output the 4 byte message id */
/* if (row < CHAR_HEIGHT) {
setCursor(row, 0);
printf("id: %x %x %x %x",
msg->id[0], msg->id[1], msg->id[2], msg->id[3]);
++row;
}*/
SSN = HIGH;
return row;
}
void move_to_next_message() {
if (cur_msg_ != last_msg_) {
msg_buffer_[cur_msg_].attr &= ~MSG_ATTR_NEW;
cur_msg_ = (cur_msg_ + 1) % NUM_MESSAGES;
}
}
void move_to_prev_message() {
if (cur_msg_ != first_msg_) {
cur_msg_ = (cur_msg_ + NUM_MESSAGES - 1) % NUM_MESSAGES;
}
}
/* Public API. */
void inbox_init() {
cur_msg_ = 0;
first_msg_ = 0;
last_msg_ = 0;
/* Provide some intro instruction messages. */
ADD_TEST_MSG(0, "Welcome to grlltech.", 0);
ADD_TEST_MSG(1, "Scroll messages with the wheel on the left.", 0);
ADD_TEST_MSG(2, "Hit menu to switch to compose view, and menu again to return.", 0);
ADD_TEST_MSG(3, "Press Enter while composing to send your message.", 0);
last_msg_ = 3;
}
void inbox_draw() {
uint8_t row, msg;
clear();
row = 0;
for (msg = cur_msg_;
msg <= last_msg_ && row < CHAR_HEIGHT;
msg = (msg + 1) % NUM_MESSAGES) {
row = draw_message(&msg_buffer_[msg], row);
}
}
void inbox_handle_keypress(uint8_t key) {
switch (key) {
case '^':
case '<':
move_to_prev_message();
inbox_draw();
break;
case KDWN:
case '>':
move_to_next_message();
inbox_draw();
break;
}
}
void inbox_push_message(const char *message, bit mine, const uint8_t* id) {
uint8_t msg;
/* See if we have this message already. */
for (msg = first_msg_;
msg <= last_msg_ % NUM_MESSAGES;
msg = (msg + 1) % NUM_MESSAGES) {
if (!memcmp(id, msg_buffer_[msg].id, 4)) {
/* If this is one of ours, confirm that we got a reply. */
if (msg_buffer_[msg].attr & MSG_ATTR_MINE) {
msg_buffer_[msg].attr |= MSG_ATTR_SENT;
}
return;
}
}
/* If inbox is full, drop the oldest message. */
if (((last_msg_ + 1) % NUM_MESSAGES) == first_msg_) {
first_msg_ = (first_msg_ + 1) % NUM_MESSAGES;
}
last_msg_ = (last_msg_ + 1) % NUM_MESSAGES;
strcpy(msg_buffer_[last_msg_].text, message);
memcpy(msg_buffer_[last_msg_].id, id, 4);
msg_buffer_[last_msg_].attr = MSG_ATTR_NEW;
if (mine) {
msg_buffer_[last_msg_].attr |= MSG_ATTR_MINE;
}
}
|
C
|
# include <stdio.h>
# include <stdlib.h>
# include <unistd.h>
int main(int argc, char * argv[]){
int pid, status = 0;
int var = 33; // cette variable sera copiée
pid = fork();
if (pid < 0) {
perror("fork"); // echec lors de la creation
return -1 ;
}
if (pid == 0) { // enfant
printf("Je suis l'enfant, pid=%d\n", getpid());
printf("Mon parent est %d\n", getppid());
var += 4;
printf("var chez l'enfant = %d\n", var);
sleep(3);
_exit(0); // "it is wrong to call exit
// since buffered data would then be flushed twice"
}
else { // parent
printf("Je suis le parent, pid=%d\n", getpid());
printf("J'attends mon enfant\n");
var += 1;
printf("var chez le parent = %d\n", var);
wait(&status); // la fin du parent ne doit pas faire
// de l'enfant un zombie
printf("Mon enfant a retourné, status=%d\n", status);
}
return 0;
}
|
C
|
#ifndef MISC_C
#define MISC_C
/********************************************************************/
/* PolyWorld: An Artificial Life Ecological Simulator */
/* by Larry Yaeger */
/* Copyright Apple Computer 1990,1991,1992 */
/********************************************************************/
// misc.C: miscellaneous useful short procedures
#include "basicincludes.h"
char tempstring[256];
char* concat(cchar* s1, cchar* s2)
{
char* s = new char[strlen(s1)+strlen(s2)+1];
strcpy(s,s1);
strcat(s,s2);
return s;
}
char* concat(cchar* s1, cchar* s2, cchar* s3)
{
char* s = new char[strlen(s1)+strlen(s2)+strlen(s3)+1];
strcpy(s,s1);
strcat(s,s2);
strcat(s,s3);
return s;
}
char* concat(cchar* s1, cchar* s2, cchar* s3, cchar* s4)
{
char* s = new char[strlen(s1)+strlen(s2)+strlen(s3)+strlen(s4)+1];
strcpy(s,s1);
strcat(s,s2);
strcat(s,s3);
strcat(s,s4);
return s;
}
char* concat(cchar* s1, cchar* s2, cchar* s3, cchar* s4, cchar* s5)
{
char* s= new char[strlen(s1)+strlen(s2)+strlen(s3)+strlen(s4)+strlen(s5)+1];
strcpy(s,s1);
strcat(s,s2);
strcat(s,s3);
strcat(s,s4);
strcat(s,s5);
return s;
}
char* concat(cchar* s1, cchar* s2, cchar* s3, cchar* s4, cchar* s5, cchar* s6)
{
char* s= new char[strlen(s1)+strlen(s2)+strlen(s3)+strlen(s4)+strlen(s5)+
strlen(s6)+1];
strcpy(s,s1);
strcat(s,s2);
strcat(s,s3);
strcat(s,s4);
strcat(s,s5);
strcat(s,s6);
return s;
}
char* concat(cchar* s1, cchar* s2, cchar* s3, cchar* s4, cchar* s5, cchar* s6,
cchar* s7)
{
char* s= new char[strlen(s1)+strlen(s2)+strlen(s3)+strlen(s4)+strlen(s5)+
strlen(s6)+strlen(s7)+1];
strcpy(s,s1);
strcat(s,s2);
strcat(s,s3);
strcat(s,s4);
strcat(s,s5);
strcat(s,s6);
strcat(s,s7);
return s;
}
char* itoa(long i)
{
char* b = new char[256];
sprintf(b,"%d\0",i);
char* a = new char[strlen(b)+1];
strcpy(a,b);
delete b;
return a;
}
char* ftoa(float f)
{
char* b = new char[256];
sprintf(b,"%g\0",f);
char* a = new char[strlen(b)+1];
strcpy(a,b);
delete b;
return a;
}
float logistic(cfloat x, cfloat slope)
{
return (1.0 / (1.0 + exp(-1 * x * slope)));
}
// end of misc.C
#endif MISC_C
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strcat.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: szverhov <szverhov@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/07/26 14:31:43 by szverhov #+# #+# */
/* Updated: 2017/11/03 12:27:15 by szverhov ### ########.fr */
/* */
/* ************************************************************************** */
#include "./push_swap.h"
t_stack *ft_new_node(int i, int grup)
{
t_stack *stack;
if (!(stack = (t_stack*)malloc(sizeof(t_stack))))
return (0);
stack->num = i;
stack->grup = grup;
stack->next = 0;
return (stack);
}
int ft_add_node(t_stack **stack, int i, int grup)
{
t_stack *tmp;
if (stack == 0 || *stack == 0)
return (0);
tmp = (*stack);
while (tmp->next)
tmp = tmp->next;
if (!(tmp->next = ft_new_node(i, grup)))
return (0);
return (1);
}
int ft_check_shit(char *s1, const char *s2)
{
if (*s1 == '-' || *s1 == '+')
s1++;
if (*s2 == '-' || *s2 == '+')
s2++;
if (*s1 == '0' && *(s1 + 1) != '\0')
while (*s1 == '0' && *(s1 + 1) != '\0')
s1++;
if (*s2 == '0' && *(s2 + 1) != '\0')
while (*s2 == '0' && *(s2 + 1) != '\0')
s2++;
if (*s1 == '0' && *s2 == '0')
return (0);
return (1);
}
int ft_strcmp_spec(char *s1, const char *s2)
{
if (!ft_check_shit(s1, s2))
return (0);
if ((*s1 == '+' && *s2 != '-'))
s1++;
if ((*s2 == '+' && *s1 != '-'))
s2++;
if ((*s1 == '-' && *s2 == '-') || (*s1 == '+' && *s2 == '+'))
{
s1++;
s2++;
}
if (*s1 == '0' && *(s1 + 1) != '\0')
while (*s1 == '0' && *(s1 + 1) != '\0')
s1++;
if (*s2 == '0' && *(s2 + 1) != '\0')
while (*s2 == '0' && *(s2 + 1) != '\0')
s2++;
while ((unsigned char)*s1 != 0 || (unsigned char)*s2 != 0)
{
if ((unsigned char)*s1 - (unsigned char)*s2 != 0)
return ((unsigned char)*s1 - (unsigned char)*s2);
s1++;
s2++;
}
return (0);
}
|
C
|
// ARGS: -cmpLt C1 C2 -tex
void printf(int i)
int scanf(int i)
int nondet()
void C1()
{
int count=1;
while (count <= 4)
{
printf(count);
count = count + 1;
}
}
void C2()
{
int count=1;
int number;
number = nondet();
printf(count);
number = scanf(2);
while (number >= 0 && count <= 4)
{
//printf(count);
count = count + 1;
}
}
void main() { C1(); C2(); }
|
C
|
#include<stdio.h>
#include<stdlib.h>
#define ARR_LEN 10
#define PT(arr,len) for(int i=0;i<len;i++){\
printf("%d,",arr[i]); \
}
void
main()
{
int arr[ARR_LEN] = {10,9,12,15,18,2,7,9,31,20};
printf("------------原数组------------------\n");
PT(arr,ARR_LEN);
int remain_start;
for(int i = 0;i<ARR_LEN -1;i++){
remain_start = i;
int max = arr[remain_start],max_index = remain_start;
for(int j = i+1;j < ARR_LEN;j++){
if(max < arr[j]){
max = arr[j];
max_index = j;
}
}
if(remain_start != max_index){
arr[max_index] = arr[remain_start];
arr[remain_start] = max;
}
printf("\n---------i:%d - ----------\n",i);
PT(arr,ARR_LEN);
}
}
|
C
|
#include "hashtable.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
// Main program runner.
int main(int argc, char *argv[]) {
// Arguments for getting the appropriate file.
FILE *fp;
char *filename;
// Create the actual hashtable.
hashtable *hash = createtable(1);
// Set the node to NULL.
struct node *node = NULL;
// Max of 50 characters.
char word[50];
if (argc < 2) {
printf("Missing filename\n");
return(1);
}
else {
filename = argv[1];
printf(" Filename: %s\n ", filename);
}
fp = fopen(filename, "r");
/* Load data from txt file to the hash table */
while(1) {
if(fscanf(fp, "%s", word) != 1) {
break;
}
if(ispunct(word[strlen(word) -1])) {
*(word + strlen(word) - 1) = '\0';
}
if(strlen(word) > 0) {
node = add(hash, word, 1);
node->frequency++;
}
}
fclose(fp);
frequencyCounter(hash);
}
|
C
|
#include <stdio.h>
#include <string.h>
int main()
{
char aa[100];
gets(aa);
int i,j,k;
j=0;
for(i=0;aa[i]!='\0';i++){
j++;
}
printf("%d",j);
}
|
C
|
#include <stdio.h>
#include <string.h> //string library
/* Payton Harrison
* Lab 7, CSCI 112
* 11/7/18
*/
//method to get input from the user
int getInput(void){
//Instructions to user about what to input
printf("\n");
printf("Please enter a word to check whether or not it is a palindrome.\n");
printf("Enter the word 'stop' to stop the program.\n");
printf("\n");
char inputWord[100]; //arbitrary string size
//flag for while loop condition
int stop = 0;
//while loop to keep collecting words until "STOP" "stop" or "Stop" is entered
while(stop != 1){
//print statement for context
printf("Word: ");
//scan for string, save to char array
scanf("%s",&inputWord);
//check to see if stop is entered, capital or lowercase
if(strcmp(inputWord, "STOP") == 0 || //if value is 0, that means s1 and s2 are equal
strcmp(inputWord, "stop") == 0 ||
strcmp(inputWord, "Stop") == 0){
//if stop is entered, set flag to "1" so that loop stops collecting words
stop = 1;
}
//if word is not stop, call subfunction
else{
//call subfunction
int n = strlen(inputWord);
checkPalindrome(inputWord, 0, (n-1)); //word and index start/end number
}
}
//exit without errors
return(0);
}
//method to check if string is a palindrome
int checkPalindrome(char inputWord[], int start, int end){
//base case: if there is only one character or 2 characters left (odd or even word)
if(start == end || (start + 1) == end){
printf(" %s IS a palindrome.\n",inputWord);
}
//if the first and last characters do not match
else if(inputWord[start] != inputWord[end]){
printf(" %s is NOT a palindrome.\n",inputWord);
}
//if there are more than 2 characters, check if middle substring is also palindrome or not
else if(start < end){
//recusrive call
checkPalindrome(inputWord, (start + 1), (end - 1));
}
//exit without errors
return(0);
}
//main method to call submethods
int main(void){
//call subfunction
getInput();
//exit without errors
return(0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "getexeccounts.h"
void usage() {
printf("You must enter a pid to get the exec counts.\n");
exit(EXIT_FAILURE);
}
int main(int argc, char **argv) {
int pid;
int pArray[] = {0, 0, 0, 0};
if (argc < 2) usage();
pid = atoi(argv[1]);
if (!kill(pid, 0)) {
printf("No process found with pid: %d\n", pid);
exit(EXIT_FAILURE);
}
getExecCounts(pid, pArray);
printf("pid %d:\n", pid);
printf("\t%d\tfork\n", pArray[0]);
printf("\t%d\tvfork\n", pArray[1]);
printf("\t%d\texecve\n", pArray[2]);
printf("\t%d\tclone\n", pArray[3]);
return EXIT_SUCCESS;
}
|
C
|
#include<stdio.h>
#include<string.h>
void main()
{
int a[100],i,b,c,sum=0;
printf("\n Enter the string");
gets(a);
b=strlen(a);
for(i=0;i<b;i++)
{
if(!((0<=a[i])&&(a[i]<=9))||(('a'<=a[i])&&(a[i]<='z')))
sum=sum+1;
}
printf("\n no.of special characters=%d",sum);
getch();
}
|
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_3__ TYPE_1__ ;
/* Type definitions */
typedef size_t uint32_t ;
typedef int int64_t ;
struct TYPE_3__ {size_t buffer_end; size_t buffer_start; int /*<<< orphan*/ ** buffer; } ;
typedef TYPE_1__ Packets_Array ;
typedef int /*<<< orphan*/ Packet_Data ;
/* Variables and functions */
size_t CRYPTO_PACKET_BUFFER_SIZE ;
int /*<<< orphan*/ free (int /*<<< orphan*/ *) ;
int /*<<< orphan*/ memcpy (int /*<<< orphan*/ *,int /*<<< orphan*/ *,int) ;
__attribute__((used)) static int64_t read_data_beg_buffer(Packets_Array *array, Packet_Data *data)
{
if (array->buffer_end == array->buffer_start)
return -1;
uint32_t num = array->buffer_start % CRYPTO_PACKET_BUFFER_SIZE;
if (!array->buffer[num])
return -1;
memcpy(data, array->buffer[num], sizeof(Packet_Data));
uint32_t id = array->buffer_start;
++array->buffer_start;
free(array->buffer[num]);
array->buffer[num] = NULL;
return id;
}
|
C
|
//page 367
#include<stdio.h>
#include<string.h>
int main()
{
char name[10];
char name1[150];
char name2[10];
char name3[10];
gets(name);//it get spaces and return address of pointer which is passed to it i.e name
fgets(name1,150,stdin);//it get spaces and reads upto maximum size
printf("string =%s \n",name);
printf("string =%s \n",name1);
scanf("%5s",name2);//it only scans upto 5
scanf("%s",name3);//scanf terminate on 2 conditions : enter and space. if we enter hhhhh gggggg then it takes hhhhh and it points at starting of gggggg.next scanf starts scanning from position which it lefts.so it reads from gggggg wothout executing next scanf
printf("string =%s \n",name2);//outputs hhhhh
printf("string =%s \n",name3);//outputs gggggg
return 0;
}
|
C
|
#include <main-nds.h>
#include <nds/font-bdf.h>
#include <nds/ppm-lite.h>
void draw_text(struct font *fnt,
char *str,
int x, int y,
u16 *dest)
{
int w, h;
struct ppm *img;
text_dims(fnt, str, &w, &h);
img = alloc_ppm(w, h);
draw_string(fnt, str, img, 0, 0, -1, -1);
draw_ppm(img, dest, x, y, 256);
free_ppm(img);
}
void draw_colour_text(struct font *fnt,
char *str,
int x, int y,
u16 *dest,
int fg, int bg)
{
int w, h;
struct ppm *img;
text_dims(fnt, str, &w, &h);
img = alloc_ppm(w, h);
draw_string(fnt, str, img, 0, 0, fg, bg);
draw_ppm(img, dest, x, y, 256);
free_ppm(img);
}
void draw_char(int x, int y, char c, u16b *dest, struct font *font) {
char str[2] = { 0, 0 };
str[0] = c;
draw_text(font, str, x, y, dest);
}
void draw_color_char(int x, int y, char c, int fg, int bg, u16b *dest,
struct font *font) {
int fgc = -1, bgc = -1;
if (fg >= 0) fgc = fg & 0xF;
if (bg >= 0) bgc = bg & 0xF;
char str[2] = { 0, 0 };
str[0] = c;
draw_colour_text(font, str, x, y, dest, fgc, bgc);
}
|
C
|
// ls - list files and directories inside a directory
#include <dirent.h>
#include <stdbool.h>
#include <stdio.h>
#include <unistd.h>
#include "constants.h"
void list_items(DIR *directory, bool show_all);
int main(int argc, char **argv) {
int arg_count = argc;
char **arguments = argv;
bool show_all = false;
// if the `-a` flag is given, include hidden files.
int c = getopt(arg_count, arguments, "a");
if (c == 'a') {
arg_count--; // obviously we should ignore the flag as an argument
arguments++;
show_all = true;
}
if (arg_count == 1) { // no arguments? - use the current directory
char current_dir[MAX_STRING_SIZE];
getcwd( current_dir, sizeof(current_dir) );
DIR *directory = opendir(current_dir);
list_items(directory, show_all);
}
while (--arg_count > 0) {
DIR *directory = opendir(*++arguments);
if (directory == NULL) {
perror(*arguments);
return 1;
}
list_items(directory, show_all);
}
printf("\n");
}
void list_items(DIR *directory, bool show_all) {
struct dirent *item;
while ( (item = readdir(directory)) ) {
char *item_name = item -> d_name;
if ( item_name[0] == '.' && show_all ) {
printf("%s ", item_name);
} else if ( item_name[0] != '.' ) {
printf("%s ", item_name);
}
}
}
|
C
|
#include "include.h"
#include "structure.h"
#include "function.h"
double frand(void);
double sfrand(long *);
int size_float = sizeof(float);
int size_int = sizeof(int);
main(int ac,char **av)
{
struct statdata shead1;
float *s1;
char infile[128];
char outfile[128];
int inbin = 0;
int outbin = 0;
int it;
float add_rand = 0.0;
setpar(ac,av);
mstpar("infile","s",infile);
mstpar("outfile","s",outfile);
getpar("inbin","d",&inbin);
getpar("outbin","d",&outbin);
mstpar("add_rand","f",&add_rand);
endpar();
s1 = NULL;
s1 = read_wccseis(infile,&shead1,s1,inbin);
if(add_rand > (float)(0.0))
{
for(it=0;it<shead1.nt;it++)
s1[it] = s1[it] + add_rand*frand();
}
write_wccseis(outfile,&shead1,s1,outbin);
}
static long frandx = 1;
/* frand() returns a uniform distribution of random numbers
* in the range -1.0 -> 1.0.
*/
double frand(void)
{
frandx = (frandx * 1103515245 + 12345) & 0x7fffffff;
return((double)(frandx)/1073741824.0 - 1.0);
}
/* sfrand() returns a uniform distribution of random numbers
* in the range -1.0 -> 1.0.
*/
double sfrand(long *seed)
{
*seed = ((*seed) * 1103515245 + 12345) & 0x7fffffff;
return((double)(*seed)/1073741824.0 - 1.0);
}
|
C
|
#include <stdio.h>
int main(int argc, char** args){
int af, ac, bf, bc, i, j, k;
printf("Numero de renglonesde la matriz A-->");
scanf("%d", &af);
printf("Numero de columnas de la matriz A-->");
scanf("%d", &ac);
printf("Numero de renglones de la matriz B-->");
scanf("%d", &bf);
printf("Numero de columnas de la matriz B-->");
scanf("%d", &bc);
if(ac!=bf){
printf("no es posible hacer la multiplicación\n");
system("pause");
return 0;
}
int A[af][ac], B[bf][bc], C[af][bc]; /*Rutina para cargar los valores*/
for(i=0;i<af;i++){
for(j=0;j<ac;j++){
printf("Escribe el valor de la matriz 1 (%d, %d)-->",i+1, j+1);
scanf("%d", &A[i][j]);
}
}
printf("\n\n");
for(i=0;i<bf;i++){
for(j=0;j<bc;j++){
printf("Escribe el valor de la matriz 2 (%d, %d)-->", i+1, j+1);
scanf("%d", &B[i][j]);
}
}
for(i=0;i<af;i++){
for(j=0;j<bc;j++){
C[i][j]=0;
for(k=0;k<ac;k++){
C[i][j]=(C[i][j]+(A[i][k]*B[k][j]));
}
}
}
/*Rutina para imprimir*/
printf("\n\n\t\t\t Matriz A");
printf("\n");
for(i=0;i<af;i++){
printf("\n\t\t");
for(j=0;j<ac;j++){
printf(" %6d ", A[i][j]);
}
}
printf("\n\n\t\t\t Matriz B");
printf("\n");
for(i=0;i<bf;i++){
printf("\n\t\t");
for(j=0;j<bc;j++){
printf(" %6d ", B[i][j]);
}
}
printf("\n\n\t\t\t Matriz C");
printf("\n");
for(i=0;i<af;i++){
printf("\n\t\t");
for(j=0;j<bc;j++){
printf(" %6d ", C[i][j]);
}
}
printf("\n");
}
|
C
|
#include "LazyFibonacci.h"
#include <stdlib.h>
#define MAX_SIZE 100
fiboNum_t lazyFibonacci(fiboNum_t n)
{
// create array with beginning of fibonacci sequence
static fiboNum_t fiboNumbers[MAX_SIZE] = { 0, 1 };
static size_t fiboNumSize = 2;
// if the result already exists, don't calculate
fiboNum_t result;
if (n <= fiboNumSize)
{
result = fiboNumbers[n];
}
// if the results don't exist, calculate from the last value
else
{
for (size_t index = fiboNumSize; index <= n; ++index)
{
fiboNumbers[index] = fiboNumbers[index - 1] + fiboNumbers[index - 2];
}
fiboNumSize = n;
result = fiboNumbers[n];
}
return result;
}
|
C
|
//
// This file is part of ChuniX and is released under the terms of
// GNU GPLv3 License, see License for details.
//
// Copyright (C) 2014, Chunis Deng (<chunchengfh@gmail.com>)
//
#include <types.h>
#include <heap.h>
#include <mmu.h>
#include <printf.h>
#include "../kern/task.h"
extern struct task *current;
static void glue_chunk (struct heap_head *chunk);
static void split_chunk (struct heap_head *chunk, uint32_t len);
static void free_chunk (struct heap_head *chunk);
static void alloc_chunk (uint32_t start, uint32_t len);
void heap_init(void)
{
// nothing needed to do here
}
// return a pointer to a chunk of >= n bytes memery
void *kmalloc(uint32_t n)
{
uint32_t chunk_start;
struct heap_head *curp = current->heap_start, *prevp = NULL;
n += sizeof(struct heap_head);
while(curp){
if(curp->free == 1 && curp->len >= n){
split_chunk(curp, n);
curp->free = 0;
return (void *)((uint32_t)curp + sizeof(struct heap_head));
}
prevp = curp;
curp = curp->next;
}
// no big enough hole found
if(prevp){
chunk_start = (uint32_t)prevp + prevp->len;
} else {
chunk_start = HEAP_START;
current->heap_start = (struct heap_head *)chunk_start;
}
alloc_chunk(chunk_start, n);
curp = (struct heap_head *)chunk_start;
curp->prev = prevp;
curp->next = NULL;
curp->free = 0;
curp->len = n;
if(prevp)
prevp->next = curp;
return (void *)(chunk_start + sizeof(struct heap_head));
}
// free a chunk of memory allocated with kmalloc for usable again
void kfree(void *p)
{
struct heap_head *head;
head = (struct heap_head *)((uint32_t)p - sizeof(struct heap_head));
head->free = 1;
glue_chunk(head);
}
static void alloc_chunk (uint32_t start, uint32_t len)
{
pte_t *page;
while(start + len > current->heap_top){
page = V2P(PTE_ADDR(kalloc_page()));
mappages(current->pgdir, current->heap_top, page, PGSIZE, PTE_P | PTE_W);
current->heap_top += PGSIZE;
}
}
static void free_chunk (struct heap_head *chunk)
{
pte_t *page;
if(chunk->prev == NULL)
current->heap_start = NULL;
else
chunk->prev->next = NULL;
while((uint32_t)chunk <= (current->heap_top - PGSIZE)){
current->heap_top -= PGSIZE;
page = pgdir_walk(current->pgdir, current->heap_top, 0);
assert(page);
unmap_page(current->pgdir, current->heap_top); // also kfree_page(page) there
}
}
// after split, the left space size need to >= (sizeof(heap_head) + 1) bytes.
// otherwise we won't bother to split it
static void split_chunk (struct heap_head *chunk, uint32_t len)
{
struct heap_head *new;
uint32_t len_left = chunk->len - len;
if(len_left <= sizeof(struct heap_head))
return;
new = (struct heap_head *)((uint32_t)chunk + len);
new->free = 1;
new->len = len_left;
chunk->len = len;
new->prev = chunk;
new->next = chunk->next;
chunk->next->prev = new;
chunk->next = new;
}
static void glue_chunk (struct heap_head *chunk)
{
// try to glue right side first
if(chunk->next && chunk->next->free == 1){
chunk->len += chunk->next->len;
chunk->next->next->prev = chunk;
chunk->next = chunk->next->next;
}
// then try to glue left side
if(chunk->prev && chunk->prev->free == 1){
chunk->prev->len += chunk->len;
chunk->prev->next = chunk->next;
if(chunk->next)
chunk->next->prev = chunk->prev;
chunk = chunk->prev;
}
// check if chunk is on the top of heap. if so, try to free it.
if(chunk->next == NULL)
free_chunk(chunk);
}
void dump_heap(void)
{
struct heap_head *p = current->heap_start;
printk("dump heap:\n");
while(p){
printk("addr: %x, offset: %d, len = %d = 12 + %d, free: %d\n",
(uint32_t)p, ((uint32_t)p - HEAP_START),
p->len, (p->len - 12), p->free);
p = p->next;
}
}
void test_kmalloc_1(void)
{
char *p, *q;
p = kmalloc(20);
dump_heap();
q = kmalloc(10);
dump_heap();
kfree(p);
dump_heap();
kfree(q);
dump_heap();
printk("done\n");
}
void test_kmalloc_2(void)
{
char *p, *q, *r, *s, *t;
p = kmalloc(32);
printk("&p = %x\n", p);
strcpy(p, "hello kmalloc, hello kmalloc");
printk("p = %s\n", p);
q = kmalloc(40);
printk("&q = %x\n", q);
strcpy(q, "test again");
printk("q = %s\n", q);
kfree(p);
printk("p = %s\n", p); // not overwrited yet
r = kmalloc(10);
printk("&r = %x\n", r);
strcpy(r, "check r");
printk("r = %s\n", r);
s = kmalloc(15); // s should go after q
printk("&s = %x\n", s);
strcpy(s, "how about s?");
printk("s = %s\n", s);
printk("p = %s\n", p); // should be the same as r
t = kmalloc(8);
printk("&t = %x\n", t); // t should between r and q
printk("t = %s\n", t); // should equal to "malloc"
dump_heap();
kfree(r);
kfree(s);
dump_heap();
kfree(q);
kfree(t);
printk("kmalloc() works\n");
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct node
{
int data;
struct node *link1;
struct node *link2;
};
int main()
{
int i,m,n,l;
char a[50];
scanf("%d",&m);
scanf("%d",&n);
getchar();
fgets(a,50,stdin);
l=(strlen(a)/2);
int ar[l];
int dd=0,r;
for(i=0;i<strlen(a);i++)
{
if((int)a[i]>=48)
{
r=(int)a[i]-48;
ar[dd++]=r;
}
}
l++;
struct node *p,*h;
p=h=(struct node*)malloc(sizeof(struct node));
p->link1=NULL;
p->data=m;
for(i=0;i<l;i++)
{
p->link2=(struct node*)malloc(sizeof(struct node));
p=p->link2;
p->data=ar[i];
}
p->link2=(struct node*)malloc(sizeof(struct node));
p=p->link2;
p->data=n;
p->link2=NULL;
p=h;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->link2;
}
}
|
C
|
#include "api.h"
int main()
{
Pilha *p1 = cria_pilha();
Pilha *p2 = cria_pilha();
push_operando(2, p1);
push_operando(5, p1);
push_operando(9, p1);
push_operando(11, p1);
pop(p1);
pop(p1);
push_operador('+', p2);
push_operador('-', p2);
pop(p2);
imprime_pilha_double(p1);
imprime_pilha_char(p2);
libera_pilha(p1);
libera_pilha(p2);
free(p1);
free(p2);
return 0;
}
|
C
|
/**
******************************************************************************
* @file mysqlite.c
* @author Dragon.Chen
* @version V1.0.0
* @date 02-28-2013
* @brief 为C语言操作MySQL数据库,提供一些增删改查的函数接口
******************************************************************************
* @attention
*
******************************************************************************
*/
#ifndef __MYSQLX__H__
#define __MYSQLX__H__
#include <mysql/mysql.h>
#include "includes.h"
/**
* @brief 链接数据库
* @param MySQL数据结构、数据库用户名、密码、数据库名
* @retval -1:链接失败,0:链接成功
*/
int connectToDatabse(MYSQL** conn_ptr, char* name, char* password, char* database_name);
/**
* @brief 插入数据
* @param MySQL数据结构、执行语句
* @retval -1:链接成功,0:链接失败
*/
int insertDataIntoDatabase(MYSQL* conn_ptr, char* sql);
/**
* @brief 删除数据
* @param MySQL数据结构、执行语句
* @retval -1:链接成功,0:链接失败
*/
int deleteDataFromDatabase(MYSQL* conn_ptr, char* sql);
/**
* @brief 修改数据
* @param MySQL数据结构、执行语句
* @retval -1:链接成功,0:链接失败
*/
int updateDataFromDatabase(MYSQL* conn_ptr, char* sql);
/**
* @brief 查询数据
* @param MySQL数据结构、执行语句
* @retval 查询失败返回NULL,反之返回查询的数据
*/
MYSQL_RES* queryDataFromDatabase(MYSQL* conn_ptr, char* sql);
/**
* @brief 关闭数据库
* @param MySQL数据结构、查询结果
* @retval 无
*/
void closeDatabase(MYSQL* conn_ptr, MYSQL_RES* result);
#endif
|
C
|
#include<stdio.h>
int main()
{
char str[50][50];
int arr[50];
int size;
scanf("%d",&size);
for(int i=0;i<size;i++)
{
fflush(stdin);
gets(str[i]);
}
printf("before sorting : \n");
for(int i=0;i<size;i++)
{
puts(str[i]);
}
int i=0,count=0;
printf("No. of vowels : \n");
while(i<size) {
int j=0;
count=0;
while(str[i][j]!='\0'){
if(str[i][j]=='a'||str[i][j]=='A'||str[i][j]=='e'||str[i][j]=='E'||str[i][j]=='i'||str[i][j]=='I'||str[i][j]=='o'||str[i][j]=='O'||str[i][j]=='U'||str[i][j]=='u'){
count++;
}
j++;}
printf("%d\n",count);
i++;
}
return 0;
}
|
C
|
#include <stdio.h>
void usage() {
printf("Usage: nproc [options]\n");
printf("Options:\n");
printf(" -a, --all\t\tPrint the number of installed processors\n");
printf(" -i, --ignore=N\tIgnore (if possible) N number of available CPUs\n");
printf(" -h, --help\t\tDisplay this message\n");
printf(" -v, --version\t\tShow the version of this utility along with a "
"copyright notice\n");
printf("Default behavior:\n");
printf(" Print the number of processors available to the running process\n");
}
|
C
|
#define STRING_SIZE 255
#define MIN_SIZE 10
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include "AppTables.h"
void getData(Tables *table, int id){
Rows *tempNode = table->row;
int flag = 1;
while (tempNode != NULL){
if (tempNode->rowId == id){
printDetails(tempNode);
flag = 0;
break;
}
tempNode = tempNode->next;
}
if (flag)
printf("\nMember with ID %d not found\n", id);
}
void putData(Tables *table, char **columnNames, char **values, int index, int id){
Rows *tempRowNode = table->row;
while (tempRowNode != NULL){
if (tempRowNode->rowId == id){
for (int i = 0; i < index; ++i)
tempRowNode->columns = getColumnHead(tempRowNode->columns, columnNames[i], values[i]);
tempRowNode->commitVersion += 1;
return;
}
tempRowNode = tempRowNode->next;
}
tempRowNode = rowHead;
Rows *newRowNode = createRowNode();
for (int i = 0; i < index; ++i){
newRowNode->columns = getColumnHead(newRowNode->columns, columnNames[i], values[i]);
}
if (rowHead == NULL){
newRowNode->rowId = 1;
newRowNode->commitVersion = 1;
rowHead = newRowNode;
}
else{
while (tempRowNode->next != NULL){
tempRowNode = tempRowNode->next;
}
newRowNode->rowId = tempRowNode->rowId + 1;
newRowNode->commitVersion = getCommitVersion(newRowNode);
tempRowNode->next = newRowNode;
}
}
void deleteData(Tables *table, int id){
Rows *rowHead = table->row, *tempNode = rowHead, *prevNode = NULL;
int flag = 1;
if (rowHead != NULL && rowHead->next == NULL){
rowHead = NULL;
free(tempNode);
return;
}
while (tempNode != NULL){
if (tempNode->rowId == id){
prevNode->next = tempNode->next;
free(tempNode);
flag = 0;
break;
}
prevNode = tempNode;
tempNode = tempNode->next;
}
if (flag)
printf("\nMember ID not found\n");
}
void dropTable(char *tableName){
Tables *tempNode = tableHead, *prevNode = NULL;
int flag = 1;
if (rowHead != NULL && rowHead->next == NULL){
rowHead = NULL;
free(tempNode);
return;
}
while (tempNode != NULL){
if (strcpy(tempNode->name, tableName) == 0){
prevNode->next = tempNode->next;
free(tempNode);
flag = 0;
break;
}
prevNode = tempNode;
tempNode = tempNode->next;
}
if (flag)
printf("\nTable not found\n");
}
|
C
|
#ifndef dk_tool_ellipse_h
#define dk_tool_ellipse_h
#include <stdio.h>
#include "dk_tool_array.h"
#include "dk_tool.h"
// EllipseArray description
typedef struct tagEllipseArray
{
int number; // number of elements (pre-requisited) in the array
int count; // the current number of elements (inserted) to the array
Ellipse **ellipses;
}EllipseArray;
// Init/Dealloc
EllipseArray *createArray(int aNumber);
void freeArray(EllipseArray *anArray);
// interface
// returns index of added element OR -1 if fail
int addElement(EllipseArray *anArray, Ellipse *aEllipse);
void writeArrayToJSON(FILE *aFile, EllipseArray *anArray);
void printArray(EllipseArray* anArray);
#endif
|
C
|
#ifndef DEFINES_H
#define DEFINES_H
#include <stdio.h>
#include <wait.h>
#include <unistd.h>
#include <time.h>
#include <stdbool.h>
#include <string.h>
#include <signal.h>
#include <stdint.h>
#include <stdlib.h>
#include <sys/sem.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/ipc.h>
const key_t semaphoreSetKey = 0xabcd0101;
const key_t sharedMemoryKey = 0xabcd1010;
const size_t OVEN_SEMAPHORE_ID = 0;
const size_t TABLE_SEMAPHORE_ID = 1;
typedef struct{
int nextSpotIndex;
int spot[5];
}Oven;
typedef struct{
int nextSpotIndex;
int spot[5];
}Table;
union semun {
int val; /* Value for SETVAL */
struct semid_ds *buf; /* Buffer for IPC_STAT, IPC_SET */
unsigned short *array; /* Array for GETALL, SETALL */
struct seminfo *__buf; /* Buffer for IPC_INFO
(Linux-specific) */
};
const size_t shrMemSize = sizeof(Oven) + sizeof(Table);
int createSemaphores(){
int smphrDesc = semget(semaphoreSetKey, 2, IPC_CREAT | IPC_EXCL | 0666);
if(smphrDesc == -1){
smphrDesc = semget(semaphoreSetKey, 2, 0666);
if(smphrDesc != -1){
semctl(smphrDesc, 0, IPC_RMID);
smphrDesc = semget(semaphoreSetKey, 2, IPC_CREAT | IPC_EXCL | 0666);
}
}
return smphrDesc;
}
int createSharedMem(){
int shmDesc = shmget(sharedMemoryKey, shrMemSize, IPC_CREAT | IPC_EXCL | 0666);
if(shmDesc == -1){
shmDesc = shmget(sharedMemoryKey, 0, 0666);
if(shmDesc != -1){
shmctl(shmDesc, IPC_RMID, NULL);
shmDesc = shmget(sharedMemoryKey, shrMemSize, IPC_CREAT | IPC_EXCL | 0666);
}
}
return shmDesc;
}
unsigned long getTimestamp(){
struct timespec spec;
clock_gettime(1, &spec);
return spec.tv_sec*1000 + spec.tv_nsec / 1000000;
}
#endif
|
C
|
#include <stdio.h>
#include <mpi.h>
int main(int argc, char *argv[]){
int nproces, myrank, i, err, len;
double data1[6], data2[6];
char name[MPI_MAX_PROCESSOR_NAME];
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &nproces);
MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
err = MPI_Get_processor_name(name, &len);
printf("Proces %d en el procesador %s\n", myrank, name);
for(i=0;i<3;i++){
data1[i] = 100 * (myrank +1) + 10*i;
data2[i] = 0;
}
err = MPI_Reduce(data1, data2, 2, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
for(i=0;i<6;i++)
printf("Proceso %d ->> data1: %f, data2: %f\n", myrank, data1[i], data2[i]);
MPI_Finalize();
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(void)
{
char IPdotdec[20]; //store the decimal IP addr
struct in_addr s; //IPv4 structure
//input IP addr
printf("Please input IP addr:");
scanf("%s", &IPdotdec);
//convert
inet_pton(AF_INET, IPdotdec, (void *)&s);
printf("inet_pton: 0x%x\n", s.s_addr); //note
//reverse convert
inet_ntop(AF_INET, (void *)&s, IPdotdec, INET_ADDRSTRLEN);
printf("inet_ntop: %s\n", IPdotdec);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
void main()
{
int h1,m1,h2,m2,t,j;
scanf("%d %d",&h1,&m1);
scanf("%d %d",&h2,&m2);
t=abs((h1*60+m1)-(h2*60+m2));
j=t;
t=t/60;
j=j%60;
printf("%d %d",t,j);
}
|
C
|
#include <gtk/gtk.h>
#include <stdlib.h>
#include <string.h>
#include "_cgo_export.h"
static const gchar *interface =
"<interface>"
" <object class=\"GtkWindow\" id=\"main-window\">"
" <property name=\"title\">Go/GTK+ Demo</property>"
" <property name=\"border-width\">100</property>"
" <signal name=\"destroy\" handler=\"destroy\"/>"
" <signal name=\"delete-event\" handler=\"delete_event\"/>"
" <child>"
" <object class=\"GtkButton\" id=\"my-button\">"
" <property name=\"label\">Hello World</property>"
" <signal name=\"clicked\" handler=\"hello\"/>"
" </object>"
" </child>"
" </object>"
"</interface>";
char **return_argv;
char *return_arg(int i)
{
return return_argv[i];
}
int init(int argc, void *argv)
{
int ac, i;
GoString *args;
args = (GoString *) argv;
ac = argc;
return_argv = (char **) malloc (argc * sizeof(char *));
for (i = 0; i < argc; i++)
return_argv[i] = strndup(args[i].p, args[i].n);
/* This is called in all GTK applications. Arguments are parsed
* from the command line and are returned to the application. */
gtk_init (&ac, &return_argv);
return ac;
}
G_MODULE_EXPORT void hello( GtkWidget *widget,
gpointer data )
{
go_message(1, "Hello World");
}
G_MODULE_EXPORT gboolean delete_event( GtkWidget *widget,
GdkEvent *event,
gpointer data )
{
/* If you return FALSE in the "delete-event" signal handler,
* GTK will emit the "destroy" signal. Returning TRUE means
* you don't want the window to be destroyed.
* This is useful for popping up 'are you sure you want to quit?'
* type dialogs. */
go_message(1, "Delete!");
return FALSE;
}
G_MODULE_EXPORT void destroy( GtkWidget *widget,
gpointer data )
{
gtk_main_quit ();
go_message(0, "Destroy!");
}
void setup() {
GtkBuilder *builder;
GError *error = NULL;
GtkWidget *window;
builder = gtk_builder_new ();
gtk_builder_add_from_string (builder, interface, -1, &error);
gtk_builder_connect_signals (builder, NULL);
window = GTK_WIDGET(gtk_builder_get_object (builder, "main-window"));
gtk_widget_show_all (window);
gtk_main ();
}
|
C
|
/*
ID: ammar.q2
LANG: C
TASK: pprime
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
long int primes[10000], numprimes = 0;
long int pals[1000000], numpals = 0;
long int a, b;
FILE *fin;
FILE *fout;
int is_prime(long int i) {
int j, p = 1;
if (i < 5) return 0;
for (j = 0; j < numprimes; j++) {
if (primes[j] > sqrt(i) ) break;
if (i %primes[j] == 0) { p = 0; break; }
}
return p;
}
void pal(long int p, int n, int o) {
if (!n) {
long int x = o ? p / 10 : p;
while (p) {
x = x * 10 + p % 10;
p = p / 10;
}
if (is_prime(x) && x <= b && x >= a) fprintf(fout, "%ld\n", x);
}
else {
int i;
for (i = 0; i < 10; i++) {
pal(p*10+i, n-1, o);
}
}
}
int main () {
fin = fopen ("pprime.in", "r");
fout = fopen ("pprime.out", "w");
fscanf(fin, "%ld %ld", &a, &b);
long int i, j;
primes[0] = 2;
numprimes ++;
for (i = 3; i <= 10000; i += 2) {
int p = 1;
for (j = 0; j < numprimes; j++) {
if (primes[j] > sqrt(i)) break;
if (i % primes[j] == 0) {
p = 0;
break;
}
}
if (p) {
primes[numprimes] = i;
numprimes++;
}
}
for (i = 1; i < 9; i ++) {
for (j = 1; j < 10; j++) {
pal(j, (i-1)/2,i%2);
}
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define g -9.8
int main(void)
{
// Big mass
float M = 0.0;
// Little mass
float m = 0.0;
// Acceleration
float a = 0.0;
// Force
float F = 0.0;
// Normal force
float N = 0.0;
// Coefficient of friction
float u = 0.0;
printf("Enter M: ");
scanf("%f", &M);
printf("\nEnter m: ");
scanf("%f", &m);
printf("\nEnter a: ");
scanf("%f", &a);
// Get the Force
F = (M * (g)) - (M + m) * a;
// Get the Normal Force
N = (M * (g));
// Get the coefficient of friction
u = F/N;
printf("Friction is: %f\n", u);
return 0;
}
|
C
|
/******************************************************************************
Height of a Tree / Depth of Tree :
Here height of a tree is maximum number of nodes on root to leaf path.
base cases :
* Height of a tree with single node is considered as 1.
* Height of a tree with no node is 0.
maxDepth()
1. If tree is empty then return 0
2. Else
(a) Get the max depth of left subtree recursively i.e.,
call maxDepth( tree->left-subtree)
(a) Get the max depth of right subtree recursively i.e.,
call maxDepth( tree->right-subtree)
(c) Get the max of max depths of left and right
subtrees and add 1 to it for the current node.
max_depth = max(max dept of left subtree, max depth of right subtree) + 1
(d) Return max_depth
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
//------------------------------ Node Structure --------------------------------
struct node {
int data;
struct node* left;
struct node* right;
};
//------------------------------------------------------------------------------
//------------------------ Function to Create New Node -------------------------
struct node* newNode(int data)
{
struct node* Node = (struct node*)malloc(sizeof(struct node));
Node -> data = data;
Node -> left = NULL;
Node -> right = NULL;
return Node;
}
//------------------------------------------------------------------------------
//----------------- Function to calculate Height of the tree -------------------
int maxDepth(struct node* parent)
{
if(parent == NULL) return 0; // height = 0
int left_height = maxDepth(parent -> left); // recursively find height of left path
int right_height = maxDepth(parent -> right);// recursively find height of right path
// Compare the height of left and right path
if(left_height > right_height) return left_height + 1;
else return right_height + 1;
// return the path of the maximum height + 1 (+1 : the curent node will included in the height count)
}
int main()
{
// construction of tree
struct node* root = newNode(1);
root -> left = newNode(2);
root -> right = newNode(3);
root -> left -> left = newNode(4);
root -> left -> right = newNode(5);
// end of construction
printf("The height of this tree is : %d", maxDepth(root));
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int i,n,f=1;
int *c;
c=&f;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
*c=*c*i;
}
printf("%d",*c);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_utils_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fhenrion <fhenrion@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/11/11 10:47:58 by fhenrion #+# #+# */
/* Updated: 2019/12/13 21:50:44 by fhenrion ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
t_lst *new_lst(char *content)
{
t_lst *new;
if (!(new = malloc(sizeof(t_lst))))
return (NULL);
if (!(new->str = malloc(BUFFER_SIZE + 1)))
{
free(new);
return (NULL);
}
if (content)
str_copy(new->str, content, '\0');
else
*new->str = '\0';
new->next = NULL;
return (new);
}
size_t str_copy(char *dst, const char *src, char end)
{
size_t copylen;
copylen = 0;
while (src[copylen] != end)
{
dst[copylen] = src[copylen];
copylen++;
}
dst[copylen] = '\0';
return (copylen);
}
size_t lst_size(t_lst *lst)
{
size_t index;
size_t lstsize;
lstsize = 0;
while (lst)
{
index = 0;
while (lst->str[index] && lst->str[index] != '\n')
index++;
lstsize += index;
lst = lst->next;
}
return (lstsize + 1);
}
int lst_clear(t_lst **lst)
{
t_lst *tmp;
t_lst *release;
tmp = *lst;
while (tmp)
{
release = tmp;
tmp = tmp->next;
free(release->str);
free(release);
}
*lst = NULL;
return (-1);
}
void fd_clear(t_fdlst **fdrmn, int fd)
{
t_fdlst *current;
t_fdlst *tmp;
tmp = *fdrmn;
while (tmp->fd != fd)
{
current = tmp;
tmp = tmp->next;
}
if (tmp == *fdrmn)
*fdrmn = tmp->next;
else
current->next = tmp->next;
free(tmp->str);
free(tmp);
}
|
C
|
#include <SDL2/SDL.h>
#include <stdio.h>
#include "input.h"
InputActions *InputActions_Create()
{
InputActions *actions = malloc(sizeof(InputActions));
actions->jump=INPUT_UP;
actions->left=INPUT_UP;
actions->right=INPUT_UP;
actions->run=INPUT_UP;
actions->quit=INPUT_UP;
return actions;
}
InputActions *InputActions_PollFromSDL(InputActions *previous)
{
InputActions *actions = malloc(sizeof(InputActions)); //Copy old actions
actions = memcpy(actions, previous, sizeof(InputActions));
//Input_InitInputActions(actions);
SDL_Event e;
while(SDL_PollEvent(&e) != 0) //Retrieve all events
{
if(e.type == SDL_QUIT)
{
actions->quit = INPUT_DOWN;
}
else if (e.type == SDL_KEYDOWN || e.type == SDL_KEYUP)
{
int new_state = INPUT_DOWN;
if(e.type == SDL_KEYUP)
new_state = INPUT_UP;
switch(e.key.keysym.sym)
{
case SDLK_RIGHT:
actions->right=Input_GetNewState(new_state, previous->right);
break;
case SDLK_LEFT:
actions->left=Input_GetNewState(new_state, previous->left);
break;
case SDLK_w:
actions->run=Input_GetNewState(new_state, previous->run);
break;
case SDLK_x:
actions->jump=Input_GetNewState(new_state, previous->jump);
break;
}
}
}
actions->right=Input_GetNewState(actions->right, previous->right);
actions->left=Input_GetNewState(actions->left, previous->left);
actions->jump=Input_GetNewState(actions->jump, previous->jump);
actions->run=Input_GetNewState(actions->run, previous->run);
free(previous);
return actions;
}
void Input_InitInputActions(InputActions *actions)
{
actions->right=INPUT_UP;
actions->left=INPUT_UP;
actions->jump=INPUT_UP;
actions->run=INPUT_UP;
}
int Input_GetNewState(int current, int previous)
{
if(current==INPUT_DOWN || current==INPUT_JUSTDOWN)
{
if(previous==INPUT_UP || previous==INPUT_JUSTUP)
return INPUT_JUSTDOWN;
else
return INPUT_DOWN;
}
else
{
if(previous==INPUT_DOWN || previous==INPUT_JUSTDOWN)
return INPUT_JUSTUP;
else
return INPUT_UP;
}
}
int Input_IsAnyDown(int input)
{
if(input == INPUT_DOWN || input == INPUT_JUSTDOWN)
return 1;
else
return 0;
}
int Input_IsAnyUp(int input)
{
if(input == INPUT_UP || input == INPUT_JUSTUP)
return 1;
else
return 0;
}
|
C
|
/*! \file lcd.c \brief Character LCD driver for HD44780/SED1278 displays. */
//*****************************************************************************
//
// File Name : 'lcd.c'
// Title : Character LCD driver for HD44780/SED1278 displays
// (usable in mem-mapped, or I/O mode)
// Author : Pascal Stang
// Created : 11/22/2000
// Revised : 4/30/2002
// Version : 1.1
// Target MCU : Atmel AVR series
// Editor Tabs : 4
//
// This code is distributed under the GNU Public License
// which can be found at http://www.gnu.org/licenses/gpl.txt
//
//*****************************************************************************
#include <avr/io.h>
#include <avr/pgmspace.h>
#include "global.h"
#include "lcd.h"
char lcdPresend=1;
/*************************************************************/
/********************** LOCAL FUNCTIONS **********************/
/*************************************************************/
void lcdInitHW(void)
{
// initialize I/O ports
// initialize LCD control lines
// cbi(LCD_CTRL_PORT, LCD_CTRL_RS); // nich unbedingt ntig da nach reset sowiso alles auf 0
// cbi(LCD_CTRL_PORT, LCD_CTRL_RW);
// cbi(LCD_CTRL_E_PORT, LCD_CTRL_E);
// initialize LCD control lines to output
sbi(LCD_CTRL_DDR, LCD_CTRL_RS);
sbi(LCD_CTRL_DDR, LCD_CTRL_RW);
sbi(LCD_CTRL_E_DDR, LCD_CTRL_E);
// initialize LCD data port to input
// initialize LCD data lines to pull-up
// LCD_DATA_DDR = (LCD_DATA_DDR)&0x0F; // set data I/O lines to input (4bit)
// LCD_DATA_POUT = (LCD_DATA_POUT)|0xF0; // set pull-ups to on (4bit)
cbi(LCD_DATA_DDR_D4, LCD_DATA_D4);
sbi(LCD_DATA_PORT_D4, LCD_DATA_D4);
cbi(LCD_DATA_DDR_D5, LCD_DATA_D5);
sbi(LCD_DATA_PORT_D5, LCD_DATA_D5);
cbi(LCD_DATA_DDR_D6, LCD_DATA_D6);
sbi(LCD_DATA_PORT_D6, LCD_DATA_D6);
cbi(LCD_DATA_DDR_D7, LCD_DATA_D7);
sbi(LCD_DATA_PORT_D7, LCD_DATA_D7);
lcdPresend = 1;
}
void lcdDataPortInput(void)
{
cbi(LCD_DATA_DDR_D4, LCD_DATA_D4);
cbi(LCD_DATA_DDR_D5, LCD_DATA_D5);
cbi(LCD_DATA_DDR_D6, LCD_DATA_D6);
cbi(LCD_DATA_DDR_D7, LCD_DATA_D7);
sbi(LCD_DATA_PORT_D7, LCD_DATA_D7); // busy line pull up
}
void lcdDataPortOutput(void)
{
sbi(LCD_DATA_DDR_D4, LCD_DATA_D4);
sbi(LCD_DATA_DDR_D5, LCD_DATA_D5);
sbi(LCD_DATA_DDR_D6, LCD_DATA_D6);
sbi(LCD_DATA_DDR_D7, LCD_DATA_D7);
}
u08 lcdDataPortRead(void)
{
u08 res=0;
if(LCD_DATA_PIN_D4 & (1<<LCD_DATA_D4)) res |=16;
if(LCD_DATA_PIN_D5 & (1<<LCD_DATA_D5)) res |=32;
if(LCD_DATA_PIN_D6 & (1<<LCD_DATA_D6)) res |=64;
if(LCD_DATA_PIN_D7 & (1<<LCD_DATA_D7)) res |=128;
return res;
}
void lcdDataPortWrite(u08 data)
{
if(data&16 ) sbi(LCD_DATA_PORT_D4, LCD_DATA_D4); else cbi(LCD_DATA_PORT_D4, LCD_DATA_D4);
if(data&32 ) sbi(LCD_DATA_PORT_D5, LCD_DATA_D5); else cbi(LCD_DATA_PORT_D5, LCD_DATA_D5);
if(data&64 ) sbi(LCD_DATA_PORT_D6, LCD_DATA_D6); else cbi(LCD_DATA_PORT_D6, LCD_DATA_D6);
if(data&128) sbi(LCD_DATA_PORT_D7, LCD_DATA_D7); else cbi(LCD_DATA_PORT_D7, LCD_DATA_D7);
}
void lcdBusyWait(void)
{
unsigned char i;
int k=0;
// wait until LCD busy bit goes to zero
// do a read from control register
cbi(LCD_CTRL_PORT, LCD_CTRL_RS); // set RS to "control"
// LCD_DATA_DDR &= 0x0F; // set data I/O lines to input (4bit)
// LCD_DATA_POUT |= 0xF0; // set pull-ups to on (4bit)
lcdDataPortInput();
sbi(LCD_CTRL_PORT, LCD_CTRL_RW); // set R/W to "read"
sbi(LCD_CTRL_E_PORT, LCD_CTRL_E); // set "E" line
LCD_DELAY; // wait
if(lcdPresend)
{
while((lcdDataPortRead() & (1<<LCD_BUSY)) && k<=2000)
// while(lcdDataPortRead() & (1<<LCD_BUSY))
{
k++;
for(i=0;i<4;i++)
{
if((i%2)==0) cbi(LCD_CTRL_E_PORT, LCD_CTRL_E); // clear "E" line
if((i%2)==1) sbi(LCD_CTRL_E_PORT, LCD_CTRL_E); // clear "E" line
LCD_DELAY; // wait
LCD_DELAY; // wait
}
}
if(k>=2000) lcdPresend = 0;
}
cbi(LCD_CTRL_E_PORT, LCD_CTRL_E); // clear "E" line
// leave data lines in input mode so they can be most easily used for other purposes
}
void lcdWrite(u08 type,u08 data)
{
// write the control byte to the display controller
lcdBusyWait(); // wait until LCD not busy
if(type==LCD_WRITE_DATA) sbi(LCD_CTRL_PORT, LCD_CTRL_RS); // set RS to "data"
else cbi(LCD_CTRL_PORT, LCD_CTRL_RS); // set RS to "control"
cbi(LCD_CTRL_PORT, LCD_CTRL_RW); // set R/W to "write"
// 4 bit write
sbi(LCD_CTRL_E_PORT, LCD_CTRL_E); // set "E" line
// LCD_DATA_DDR = LCD_DATA_DDR|0xF0; // set data I/O lines to output (4bit)
lcdDataPortOutput();
//LCD_DATA_POUT= (LCD_DATA_POUT&0x0F) | (data&0xF0) ; // output data, high 4 bits
lcdDataPortWrite(data&0xF0);
LCD_DELAY; // wait
LCD_DELAY; // wait
cbi(LCD_CTRL_E_PORT, LCD_CTRL_E); // clear "E" line
LCD_DELAY; // wait
LCD_DELAY; // wait
sbi(LCD_CTRL_E_PORT, LCD_CTRL_E); // set "E" line
// LCD_DATA_POUT = (((LCD_DATA_POUT)&0x0F) | (data<<4) ); // output data, low 4 bits
lcdDataPortWrite(data<<4);
LCD_DELAY; // wait
LCD_DELAY; // wait
cbi(LCD_CTRL_E_PORT, LCD_CTRL_E); // clear "E" line
// leave data lines in input mode so they can be most easily used for other purposes
//LCD_DATA_DDR = LCD_DATA_DDR&0x0F; // set data I/O lines to input (4bit)
//LCD_DATA_POUT= LCD_DATA_POUT|0xF0; // set pull-ups to on (4bit)
lcdDataPortInput();
}
void lcdDataWrite(u08 data)
{
lcdWrite(LCD_WRITE_DATA,data);
}
void lcdControlWrite(u08 data)
{
lcdWrite(LCD_WRITE_CONTROL,data);
}
/*
u08 lcdControlRead(void)
{
// read the control byte from the display controller
register u08 data;
#ifdef LCD_PORT_INTERFACE
lcdBusyWait(); // wait until LCD not busy
#ifdef LCD_DATA_4BIT
LCD_DATA_DDR = ((LCD_DATA_DDR)&0x0F); // set data I/O lines to input (4bit)
LCD_DATA_POUT = ((LCD_DATA_POUT)|0xF0); // set pull-ups to on (4bit)
#else
outb(LCD_DATA_DDR, 0x00); // set data I/O lines to input (8bit)
outb(LCD_DATA_POUT, 0xFF); // set pull-ups to on (8bit)
#endif
cbi(LCD_CTRL_PORT, LCD_CTRL_RS); // set RS to "control"
sbi(LCD_CTRL_PORT, LCD_CTRL_RW); // set R/W to "read"
#ifdef LCD_DATA_4BIT
// 4 bit read
sbi(LCD_CTRL_PORT, LCD_CTRL_E); // set "E" line
LCD_DELAY; // wait
LCD_DELAY; // wait
data = (LCD_DATA_PIN)&0xF0; // input data, high 4 bits
cbi(LCD_CTRL_PORT, LCD_CTRL_E); // clear "E" line
LCD_DELAY; // wait
LCD_DELAY; // wait
sbi(LCD_CTRL_PORT, LCD_CTRL_E); // set "E" line
LCD_DELAY; // wait
LCD_DELAY; // wait
data |= (LCD_DATA_PIN)>>4; // input data, low 4 bits
cbi(LCD_CTRL_PORT, LCD_CTRL_E); // clear "E" line
#else
// 8 bit read
sbi(LCD_CTRL_PORT, LCD_CTRL_E); // set "E" line
LCD_DELAY; // wait
LCD_DELAY; // wait
data = inb(LCD_DATA_PIN); // input data, 8bits
cbi(LCD_CTRL_PORT, LCD_CTRL_E); // clear "E" line
#endif
// leave data lines in input mode so they can be most easily used for other purposes
#else
//sbi(MCUCR, SRW); // enable RAM waitstate
lcdBusyWait(); // wait until LCD not busy
data = *((volatile unsigned char *) (LCD_CTRL_ADDR));
//cbi(MCUCR, SRW); // disable RAM waitstate
#endif
return data;
}
*/
/*
u08 lcdDataRead(void)
{
// read a data byte from the display
register u08 data;
#ifdef LCD_PORT_INTERFACE
lcdBusyWait(); // wait until LCD not busy
#ifdef LCD_DATA_4BIT
outb(LCD_DATA_DDR, inb(LCD_DATA_DDR)&0x0F); // set data I/O lines to input (4bit)
outb(LCD_DATA_POUT, inb(LCD_DATA_POUT)|0xF0); // set pull-ups to on (4bit)
#else
outb(LCD_DATA_DDR, 0x00); // set data I/O lines to input (8bit)
outb(LCD_DATA_POUT, 0xFF); // set pull-ups to on (8bit)
#endif
sbi(LCD_CTRL_PORT, LCD_CTRL_RS); // set RS to "data"
sbi(LCD_CTRL_PORT, LCD_CTRL_RW); // set R/W to "read"
#ifdef LCD_DATA_4BIT
// 4 bit read
sbi(LCD_CTRL_PORT, LCD_CTRL_E); // set "E" line
LCD_DELAY; // wait
LCD_DELAY; // wait
data = inb(LCD_DATA_PIN)&0xF0; // input data, high 4 bits
cbi(LCD_CTRL_PORT, LCD_CTRL_E); // clear "E" line
LCD_DELAY; // wait
LCD_DELAY; // wait
sbi(LCD_CTRL_PORT, LCD_CTRL_E); // set "E" line
LCD_DELAY; // wait
LCD_DELAY; // wait
data |= inb(LCD_DATA_PIN)>>4; // input data, low 4 bits
cbi(LCD_CTRL_PORT, LCD_CTRL_E); // clear "E" line
#else
// 8 bit read
sbi(LCD_CTRL_PORT, LCD_CTRL_E); // set "E" line
LCD_DELAY; // wait
LCD_DELAY; // wait
data = inb(LCD_DATA_PIN); // input data, 8bits
cbi(LCD_CTRL_PORT, LCD_CTRL_E); // clear "E" line
#endif
// leave data lines in input mode so they can be most easily used for other purposes
#else
// memory bus read
//sbi(MCUCR, SRW); // enable RAM waitstate
lcdBusyWait(); // wait until LCD not busy
data = *((volatile unsigned char *) (LCD_DATA_ADDR));
//cbi(MCUCR, SRW); // disable RAM waitstate
#endif
return data;
}
*/
/*************************************************************/
/********************* PUBLIC FUNCTIONS **********************/
/*************************************************************/
void lcdInit()
{
// initialize hardware
lcdInitHW();
// LCD function set
lcdControlWrite(LCD_FUNCTION_DEFAULT);
// clear LCD
lcdControlWrite(1<<LCD_CLR);
//delay(60000); // wait 60ms
// set entry mode
lcdControlWrite(1<<LCD_ENTRY_MODE | 1<<LCD_ENTRY_INC);
// set display to on
//lcdControlWrite(1<<LCD_ON_CTRL | 1<<LCD_ON_DISPLAY | 1<<LCD_ON_BLINK);
lcdControlWrite(1<<LCD_ON_CTRL | 1<<LCD_ON_DISPLAY );
// move cursor to home
lcdControlWrite(1<<LCD_HOME);
// set data address to 0
// lcdControlWrite(1<<LCD_DDRAM | 0x00);
}
/*
void lcdHome(void)
{
// move cursor to home
lcdControlWrite(1<<LCD_HOME);
}
*/
/*
void lcdClear(void)
{
// clear LCD
lcdControlWrite(1<<LCD_CLR);
}
*/
/*
void lcdGotoXY(u08 x, u08 y)
{
register u08 DDRAMAddr;
// remap lines into proper order
switch(y)
{
case 0: DDRAMAddr = LCD_LINE0_DDRAMADDR+x; break;
case 1: DDRAMAddr = LCD_LINE1_DDRAMADDR+x; break;
// case 2: DDRAMAddr = LCD_LINE2_DDRAMADDR+x; break;
// case 3: DDRAMAddr = LCD_LINE3_DDRAMADDR+x; break;
default: DDRAMAddr = LCD_LINE0_DDRAMADDR+x;
}
// set data address
lcdControlWrite(1<<LCD_DDRAM | DDRAMAddr);
}
*/
// geht immer zum anfang der der zeile "y"
void lcdGotoY(u08 y)
{
// set data address
lcdControlWrite(1<<LCD_DDRAM | (0x40*y));
}
/*
void lcdPrintData(char* data, u08 nBytes)
{
register u08 i;
// check to make sure we have a good pointer
if (!data) return;
// print data
for(i=0; i<nBytes; i++)
{
lcdDataWrite(data[i]);
}
}
*/
void lcdPrintProgString(const char *str)
{
// print a string stored in program memory
register char c;
// check to make sure we have a good pointer
// if (!str) return;
// print the string until the null-terminator
while((c = pgm_read_byte(str++)))
lcdDataWrite(c);
}
void lcdPrintSpaces(unsigned char n)
{
for(;n;n--)lcdDataWrite(' ');
}
// zahlen ausgeben, eventuell mit dezimalpunkt an "pointpos" mit lnge "numDigits"
void lcdNum(signed short x,unsigned char numDigits,unsigned char pointPos)
{
unsigned char c;//,minus=0;
unsigned char firstNoneZero=0;
unsigned short divisor=1;
unsigned char pos = numDigits;
if(x<0)
{
// minus=1;
x=-x;
lcdDataWrite('-');
firstNoneZero=1;
}
for(;(numDigits>1);numDigits--) divisor*=10;
do {
// if(minus)
// {
// lcdDataWrite('-');
// minus=0;
// }
if(pointPos==pos) lcdDataWrite('.');
pos--;
c = ( unsigned char)((x/divisor)%10);
if(c||(pos<=pointPos)) firstNoneZero=1;
if((c==0)&&(firstNoneZero==0)) lcdDataWrite(' ');
else
{
lcdDataWrite(c +'0');
}
divisor /= 10;
} while (divisor);
}
|
C
|
#include <stdio.h>
void media(float a, float b, float c){
float result;
result = (a*2+b*3+c*5)/10;
if ((result>8)&&(result<=10)){
printf("%.1f\n%s\n",result,"A");
}
else if ((result>7)&&(result<=8)){
printf("%.1f\n%s\n",result,"B");
}
else if ((result>6)&&(result<=7)){
printf("%.1f\n%s\n",result,"C");
}
else if ((result>5)&&(result<=6)){
printf("%.1f\n%s\n",result,"D");
}
else{
printf("%.1f\n%s\n",result,"E");
}
}
int main(){
float a,b,c;
float result;
scanf("%f %f %f",&a,&b,&c);
media(a,b,c);
return(0);
}
|
C
|
/*
* tšGuG
* ǸG4108056050
* mWG]ݬ
* pqllGa0927554266@gmail.com
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,b,c; //ϥΪ̿JTӼƦr
int num; //JT
int temp; //Ȧsܼ
printf("пJ@ӤTƦr:");
scanf("%d",&num);
a = num/100; //ھڤTƨXTӼƦr
b = (num-a*100)/10;
c = num-(a*100+b*10);
if(a>b){
temp = a;
a = b;
b = temp;
}
if(a>c){
temp = a;
a = c;
c = temp;
}
if(b>c){
temp = c;
c = b;
b = temp;
}
if(a != 0)
printf("%d%d%d",a,b,c);
else if(b != 0)
printf("%d%d%d",b,a,c);
else if(c != 0)
printf("%d%d%d",c,a,b);
return 0;
}
|
C
|
#include"inc.h"
void ERROR(char *mess)
{
fprintf(stderr,"ERROR -> %s\n",mess);
exit(1);
}
//------------------------------- Cross section of ee -> mu mu
double eemm(double s)
{
double a;
double beta=1.-4*mmu*mmu/s;
if(beta<=0) return 0;
if(beta>=1) return 0;
beta=sqrt(beta);
a=beta*(6-2*beta*beta);
return a*pi*alpha*alpha/3./s;
}
//------------------------------- Breit-Wigner cross section
double bw(double s,double m,double Gamma,double Bee)
{
return 12*pi*Bee*Gamma*Gamma/((s-m*m)*(s-m*m)+m*m*Gamma*Gamma);
}
//------------------------------- Interference between two resonances
double interference( double s,
double m1,double Gamma1,double Bee1,double alpha1,
double m2,double Gamma2,double Bee2,double alpha2
)
{
double a = (alpha1-alpha2)/180.*pi;
double x = (s-m1*m1)*(s-m2*m2)+m1*m2*Gamma1*Gamma2;
double y = m1*Gamma1*(s-m2*m2)-m2*Gamma2*(s-m1*m1);
double aux = (x*cos(a)+y*sin(a))/(x*x+y*y);
aux = aux*12.*pi*2.*sqrt(Bee1*Bee2)*Gamma1*Gamma2;
return aux;
}
//------------------------------- int_{treshold}^{+inf}(bw(s')/(s'-s))ds'
double bw_int(double s,double m,double Gamma,double Bee)
{
double aux;
aux=((treshold2-m*m)*(treshold2-m*m)+m*m*Gamma*Gamma)/(s-treshold2)/(s-treshold2);
aux=0.5*log(aux);
aux-=(s-m*m)/m/Gamma*(pi/2+atan((m*m-treshold2)/m/Gamma));
aux*=bw(s,m,Gamma,Bee);
return aux;
}
|
C
|
//headΪβεĺ˼붼DZ㷨
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct worker
{
char id[12];
char name[10];
char sex[6];
int age;
char edu[16];
int salary;
char phone[14];
char address[32];
struct Node *next;
}LNode, *LinkList;
void mainmenu()
{
printf("\n\n\tӭʹְϢϵͳBeta.\t\n");
printf("\n\t밴Ӧѡ\t\n");
printf("\t0.̴浵\t\n");
printf("\t1.ְϢ.\t\n");
printf("\t2.ȫְϢ\t\n");
printf("\t3.ְ\t\n");
printf("\t4.ʲѯְ\t\n");
printf("\t5.ְϢ\t\n");
printf("\t6.ɾְϢ\t\n");
printf("\tܰʾڲ֮ʹô浵ܣݶʧ\t\n");
printf("\n\tϹҵѧ ƿ1707 Ʒ\n");
}
void wrong()
{
system("cls");
printf("\nһ\n");
}
void done()
{
printf("\nɣ\n");
}
void add(LinkList head)
{
int i, n;
LNode *p, *p0;//ָṹָ
p0 = head;
printf("\nӶְأ");
scanf("%d", &n);
while (p0->next != NULL)
p0 = p0->next;//һڵ㣬
for (i = 1; i <= n; i++)
{
if ((p = (LinkList)malloc(sizeof(LNode))) == NULL)//ΪַLinkListΪLNodeڴ
{
void wrong();
exit(-1);
}
printf("\n");
printf("ְĹ()");
scanf("%s", p->id);
printf("\n");
printf("ְǣ");
scanf("%s", p->name);
printf("\n");
printf("ְԱ(/Ů):");
scanf("%s", p->sex);
printf("\n");
printf("ְǣ");
scanf("%d", &p->age);
printf("\n");
printf("ְѧ(ר/ר//˶ʿ/ʿ/)");
scanf("%s", p->edu);
printf("\n");
printf("ְ¹ǣ");
scanf("%d", &p->salary);
printf("\n");
printf("ְĵ绰ǣ");
scanf("%s", p->phone);
printf("\n");
printf("ְסַǣ");
scanf("%s", p->address);
printf("\n");
p->next = NULL;//β
p0->next = p;//½Ľβ
p0 = p;
done();
}
}
void showall(LinkList head)
{
LNode *p;
p = head->next;
if (!p)//
{
wrong();
printf("ûְϢ¼룡");
}
printf("\n\t\tԱ\t\tѧ\t\t绰\t\tסַ \n");
while (p)
{
printf("%s\t%s\t%s\t%d\t%s\t%d\t%s\t%s\n", p->id, p->name, p->sex, p->age, p->edu, p->salary, p->phone, p->address);
p = p->next;
}
done();
}
void sortbysalary(LinkList head)
{
LNode *p0, *p1;//ָǴҵĹϵָ˶p1ָһڵ
p0 = head->next;
p1 = p0->next;
if (!p0)//p0֧
{
wrong();
printf("ûԱϢ¼QAQ");
exit(0);
}
int count = 0;//װãactivated
int i, j;
char id[12];//ʱݱ㣬activated
char name[10];
char sex[6];
int age;
char edu[16];
int salary;
char phone[14];
char address[32];
printf("");
//ð...
while (p0)//¼ڵ
{
count++;
p0 = p0->next;
}
for (i = 1; i <= count - 1; i++)//ðĿ-1
{
for (j = 1; j <= count - 1 - i; j++)//ÿͷβһ飬ͳײȽϴͼ1
{
p0 = head->next;//صͷ
p1 = p0->next;
while (p1)//p1p0ȴС
{
if (p0->salary > p1->salary)//p0p1УҪСǰ
{
strcpy(id, p0->id);//p0
strcpy(name, p0->name);
strcpy(sex, p0->sex);
age = p0->age;
strcpy(edu, p0->edu);
salary = p0->salary;
strcpy(phone, p0->phone);
strcpy(address, p0->address);
strcpy(p0->id, p1->id);//p1ݸp0
strcpy(p0->name, p1->name);
strcpy(p0->sex, p1->sex);
p0->age = p1->age;
strcpy(p0->edu, p1->edu);
p0->salary = p1->salary;
strcpy(p0->phone, p1->phone);
strcpy(p0->address, p1->address);
strcpy(p1->id, id);//p0ݸp1
strcpy(p1->name, name);
strcpy(p1->sex, sex);
p1->age = age;
strcpy(p1->edu, edu);
p1->salary = salary;
strcpy(p1->phone, phone);
strcpy(p1->address, address);
}
p0 = p0->next;
p1 = p1->next;
}
}
}
printf("\nˣ");
showall(head);
done();
}
void findbysalary(LinkList head)
{
int salary;
printf("ҹΪٵԱ");
scanf("%d", &salary);
int count = 0;
printf("\n\t\tԱ\t\tѧ\t\t绰\t\tסַ \n");
LNode *p;
p = head->next;
while (p)
{
if (p->salary == salary)
{
printf("%s\t%s\t%s\t%d\t%s\t%d\t%s\t%s\n", p->id, p->name, p->sex, p->age, p->edu, p->salary, p->phone, p->address);
count++;
}
p = p->next;
}
if (count == 0)
printf("ûзԱ\n");
done();
}
void rewrite(LinkList head)
{
printf("\nĵְıţ");
char id[12];
scanf("%s", id);
LNode *p;
p = head->next;
int count = 0;
while (p)
{
if (strcmp(p->id, id) == 0)
{
count++;
printf("\nѾҵ:\n");
printf("\n\t\tԱ\t\tѧ\t\t绰\t\tסַ \n");
printf("%s\t%s\t%s\t%d\t%s\t%d\t%s\t%s\n", p->id, p->name, p->sex, p->age, p->edu, p->salary, p->phone, p->address);
printf("\nĺݣ\n");
printf("ĺְǣ");
scanf("%s", p->name);
printf("\n");
printf("ĺְԱ(/Ů):");
scanf("%s", p->sex);
printf("\n");
printf("ĺְǣ");
scanf("%d", &p->age);
printf("\n");
printf("ĺְѧ(ר/ר//˶ʿ/ʿ/)");
scanf("%s", p->edu);
printf("\n");
printf("ĺְ¹ǣ");
scanf("%d", &p->salary);
printf("\n");
printf("ĺְĵ绰ǣ");
scanf("%s", p->phone);
printf("\n");
printf("ĺְסַǣ");
scanf("%s", p->address);
}
p = p->next;
}
if (count == 0)
{
wrong();
printf("ˣԡ");
}
done();
}
void del(LinkList head)
{
printf("\nɾְıţ");
char id[12];
scanf("%s", id);
LNode *p, *p0;//p0pǰһλ
p = head->next;
p0 = head;
int count = 0;
char choose;
while (p)
{
if (strcmp(p->id, id) == 0)
{
count++;
printf("\nѾҵ:\n");
printf("\n\t\tԱ\t\tѧ\t\t绰\t\tסַ \n");
printf("%s\t%s\t%s\t%d\t%s\t%d\t%s\t%s\n", p->id, p->name, p->sex, p->age, p->edu, p->salary, p->phone, p->address);
printf("\nҪɾ?Y/N");
scanf("%s", &choose);
if (choose == 'y' || choose == 'Y')
{
p0->next = p->next;
free(p);
break;
}
else
{
printf("\n˳...\n");
exit(0);
}
}
p = p->next;
p0 = p0->next;
}
if (count == 0)
{
wrong();
printf("ˣԡ");
}
done();
}
void save(LinkList L)
{
FILE *fp;
fp = fopen("worklist.txt", "wb");//дļ
LNode *p;//һùָָԭṹ壬ƶд
p = L->next;//ȻùָѾָ˵һڵ
if (fp == NULL)//ҲŴ
{
wrong();
exit(-1);
}
while (p)
{
if (fwrite(p, sizeof(LNode), 1, fp) == 1)//һ¼ֵдļ
{
p = p->next; //ָһд
}
else//
{
wrong();
exit(-1);
}
}
fclose(fp);
printf("\nڴ浵...");
done();
}
int main(void)
{
FILE *fp;
LNode *p, *p0;//p0pǰһڵ
LinkList L;//һ
L = (LinkList)malloc(sizeof(LNode));
if (!L)//鱨
{
void wrong();
exit(-1);
}
p0 = L;//p0ָڶڵָ
L->next = NULL;//
char choose;
fp = fopen("worklist.txt", "rb");//ļ
if (fp == NULL)
{
printf("\nע⣺洢ְϢıļڣǷ(Y/N)\n");
scanf("%c", &choose);
if (choose == 'y' || choose == 'Y')
{
fp = fopen("worklist.txt", "ab+");
printf("ļѴ\n");
}
else
{
printf("ļڣдְϢ!\n");
exit(0);
}
}
printf("ļҵȡ");
while (!feof(fp)) //ѭȡļ
{
p = (LinkList)malloc(sizeof(LNode));
if (!p)//鱨
{
void wrong();
exit(0);
}
if (fread(p, sizeof(LNode), 1, fp)) //ļ
{
p->next = NULL;//Ŀǰһڵ㣬û
p0->next = p;
p0 = p; //ý,
}
}
fclose(fp);
void done();
while (1)
{
mainmenu();
printf("\nѡıǣ");
int select;
scanf("%d", &select);
switch (select)
{
case 0:save(L);
break;
case 1:add(L);
break;
case 2:showall(L);
break;
case 3:sortbysalary(L);
break;
case 4:findbysalary(L);
break;
case 5:rewrite(L);
break;
case 6:del(L);
break;
default:
wrong();
break;
}
}
}
|
C
|
#include<stdio.h>
int collagen(int n)
{
if(n==1)
{
return 1;
}
if(n%2==0)
{
printf("%d ",n);
return collagen(n/2);
}
else
{
printf("%d ",n);
return collagen(3*n+1);
}
}
int main()
{
int n,g;
scanf("%d",&n);
if(g=collagen(n))
{
printf("%d ",g);
}
}
|
C
|
#include <stdio.h>
/* Ordenação por Inserção
- Compara cada elemento do vetor com seus anteriores
- Se algum dos anteriores for maior que o comparado
- Reposiciona os elementos a frente, a partir do maior, e entra na sua posição correta
*/
#define QUANT 8 // quantidade de elementos do vetor
void imprimirListaOrdenada(int vetor[], int tamanho);
int ordenar_insercao(int vetor[], int n);
int posicao_elemento(int vetor[], int ultimo, int elemento);
void deslocar_subvetor(int vetor[], int primeiro, int ultimo);
void main(){
int numeros[QUANT];
int i;
printf("\nINSIRA OS NUMEROS PARA A ORDENACAO:\n\n");
for ( i = 0; i < QUANT; i++)
{
printf("%do Numero: ", i+1);
scanf("%d", &numeros[i]);
}
ordenar_insercao(numeros, QUANT);
imprimirListaOrdenada(numeros, QUANT);
}
void imprimirListaOrdenada(int vetor[], int tamanho){
int i;
printf("\nLISTA ORDENADA:\n\n");
for ( i = 0; i < tamanho; i++)
{
printf("%d ", vetor[i]);
}
}
// Recebe o vetor e o número de elementos (n) que ele possui
// Guarda o elemento que será posicionado, a partir do vetor[1], (o vetor[0] já está posicionado)
// Compara com os anteriores e recebe o índice do que for maior em "posicao"
// Com os elementos posicionados a frente, posiciona o elemento comparado na posição que deve ficar
int ordenar_insercao(int vetor[], int n) {
int i, posicao;
int elemento;
for (i = 1; i < n; i++) {
elemento = vetor[i];
posicao = posicao_elemento(vetor, i-1, elemento);
deslocar_subvetor(vetor, posicao, i-1);
vetor[posicao] = elemento;
}
}
// Recebe o vetor, o index do vetor anterior ao elemento (ultimo) e o elemento comparado
// O elemento é comparado com todos os antecessores no vetor
// Se o elemento for menor que algum dos anteriores, é retornado o índice desse elemento
int posicao_elemento(int vetor[], int ultimo, int elemento) {
int i;
for (i = 0; i <= ultimo && vetor[i] <= elemento; i++);
return i;
}
// Recebe o vetor, o elemento que é maior ao comparado (primeiro) e o elemento comparado (ultimo)
// Repociciona todos os elementos entre eles uma posição a frente
void deslocar_subvetor(int vetor[], int primeiro, int ultimo) {
int i;
for (i = ultimo; i >= primeiro; i--) {
vetor[i+1] = vetor[i];
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <assert.h>
#include <time.h>
int main(int argc, char** argv) {
MPI_Init(NULL, NULL);
int world_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
int world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
int local_num_steps;
MPI_Status status;
if(world_rank == 0)
{
local_num_steps = 100000;
}
MPI_Bcast(&local_num_steps, 1, MPI_INT, 0, MPI_COMM_WORLD);
//printf("[%d]: After Bcast, number of step is %d\n", world_rank, local_num_steps);
// Sum the numbers locally
int num_elements_per_proc=local_num_steps/world_size;
int start_index=(world_rank*local_num_steps/world_size);
int end_index=((world_rank+1)*local_num_steps/world_size);
printf("[%d]/ %d: After Bcast, number of step is %d from %d to %d\n", world_rank,world_size,local_num_steps, start_index,end_index);
float local_sum = 0;
int i;
double step = 1.0/(double)local_num_steps;
for (i = start_index; i < end_index; i++) {
double x = (i+0.5)*step;
local_sum = local_sum + 4.0/(1.0+x*x);
}
printf("Local sum for process %d - %f, avg = %f\n",
world_rank, local_sum, local_sum / num_elements_per_proc);
// Reduce all of the local sums into the global sum
float global_sum;
MPI_Reduce(&local_sum, &global_sum, 1, MPI_FLOAT, MPI_SUM, 0,
MPI_COMM_WORLD);
// Print the result
if (world_rank == 0) {
printf("Total sum = %f, avg = %f\n", global_sum,
global_sum / (world_size * num_elements_per_proc));
}
MPI_Barrier(MPI_COMM_WORLD);
MPI_Finalize();
}
|
C
|
/*
* Matt Raymond, December 2020
* cFS Receiving Socket Library Example
*
* EECS 587, Advanced Operating Systems
* Final Project
*/
#include <stdio.h>
#include "receiving_socket.h"
// This is an example application of how to use the cFS receiving socket library
int main()
{
// allocate buffer, sockets, and incoming data. These will be controlled by the user beause they will likely
// want to access them at some point.
char buffer[MAX_BURST_LEN];
Sockets socket_data;
Incoming_Data incoming_data;
// Initialize the socket, just like any other application
if (initialize_socket(&socket_data, &incoming_data) != 0)
{
printf("There was an issue initializing the socket\n");
exit(EXIT_FAILURE);
}
while (1)
{
// The socket is considered to fail every time it doesn't find all fo the packets, therefore returning 1
// every single time except for the times that it receives packets
if (socket_run(&socket_data, buffer, &incoming_data) != 1)
{
// Print out the data just becase
printf("State_len: %d, Table_len: %d, App_len: %d, Msg_len: %d\n", incoming_data.state.len, incoming_data.sch.len, incoming_data.app.len, incoming_data.msg.len);
printf("%s\n", incoming_data.state.app_name.data);
printf("%s\n", incoming_data.state.entrypoint.data);
// Free all of the mallocs and reset all of the variables so we don't end up with memory leaks
destroy(&incoming_data);
}
sleep(1);
}
// get ready to shut down
uninitialize_socket(&socket_data);
return EXIT_SUCCESS;
}
|
C
|
#include <zebra.h>
#include "vty.h"
#include "command.h"
#include "linklist.h"
#include "memory.h"
#include "usermgmt.h"
static struct list *group_list;
static struct list *user_list;
struct login_access_map{
char *access;
int mask;
};
static const char *reserve_group[]={
"root",
NULL
};
static int is_reserve_group(const char *group)
{
const char **rg = reserve_group;
while(*rg){
if(strcmp(*rg, group) == 0)
return 1;
rg++;
}
return 0;
}
static const char *reserve_user[] = {
"root",
"admin",
NULL
};
static int is_reserve_user(const char *user)
{
const char **ru = reserve_user;
while(*ru){
if(strcmp(*ru, user) == 0)
return 1;
ru++;
}
return 0;
}
static const struct login_access_map _login_access_map[] = {
{"console", GAP_LOGIN_ACCESS_CONSOLE},
{"ssh2", GAP_LOGIN_ACCESS_SSH},
{"web", GAP_LOGIN_ACCESS_WEB},
{NULL, 0},
};
static int get_login_access_id(const char *access)
{
const struct login_access_map *login_map= _login_access_map;
while(login_map->access){
if(strcmp(access, login_map->access) == 0)
return login_map->mask;
}
return 0;
}
static struct group *sys_addgroup(const char *name)
{
if(!getgrnam(name)){
cmd_system_novty_arg("addgroup %s", name);
}
return getgrnam(name);
}
static struct group *sys_delgroup(const char *name)
{
cmd_system_novty_arg("delgroup %s", name);
return getgrnam(name);
}
DEFUN(add_group,
add_group_cmd,
"group GROUPNAME access {console|ssh2|web}",
"Management group\n"
"group name\n"
"Login access\n"
"Permit login by console\n"
"Permit login by SSH2\n"
"Permit login by Web\n"
"Description\n")
{
struct listnode *node;
struct group *group;
struct gap_mgmt_group *mg;
const char *name = argv[0];
int access = 0;
if(is_reserve_group(name))
{
vty_out(vty, "can't add a reserved group name.!%s", VTY_NEWLINE);
return CMD_ERR_NOTHING_TODO;
}
group = sys_addgroup(name);
if(!group)
{
vty_out(vty, "add group fail.%s", VTY_NEWLINE);
return CMD_SUCCESS;
}
if(argv[1]){
access += get_login_access_id(argv[1]);
}
if(argv[2])
access += get_login_access_id(argv[2]);
if(argv[3])
access += get_login_access_id(argv[3]);
/* check name */
for(ALL_LIST_ELEMENTS_RO(group_list,node,mg))
{
if(strcmp(name, mg->group_name) == 0)
break;
}
if(!mg){
mg = XCALLOC(MTYPE_TMP, sizeof(struct gap_mgmt_group));
listnode_add(group_list, mg);
mg->group_name = XSTRDUP(MTYPE_TMP, name);
}
if(access != mg->access)
mg->access = access;
if(!mg->creator)
{
mg->creator = XSTRDUP(MTYPE_TMP, vty->username);
time(&mg->createtime);
}
else
{
time(&mg->modifytime);
}
return CMD_SUCCESS;
}
DEFUN(del_group,
del_group_cmd,
"no group GROUPNAME",
NO_STR
"Manager Group\n"
"Group name\n")
{
const char *name = argv[0];
struct listnode *node, *nextnode;
struct gap_mgmt_group *mg;
if(sys_delgroup(name))
{
vty_out(vty, "group %s is used.%s", name, VTY_NEWLINE);
return CMD_ERR_NOTHING_TODO;
}
for(ALL_LIST_ELEMENTS(group_list,node,nextnode,mg))
{
printf("%p %p", node, mg);
if(strcmp(name, mg->group_name)==0)
{
LISTNODE_DETACH(group_list,node);
break;
}
}
if(mg)
{
XFREE(MTYPE_TMP, mg->group_name);
XFREE(MTYPE_TMP, mg->desc);
XFREE(MTYPE_TMP, mg->creator);
XFREE(MTYPE_TMP, mg);
}
return CMD_SUCCESS;
}
DEFUN(add_user,
add_user_cmd,
"user USERNAME group GROUPNAME",
"User maitaince\n")
{
return CMD_SUCCESS;
}
static struct cmd_node user_node={
SYS_USER_NODE,
"",
1,
};
static int user_config_write(struct vty*vty)
{
int w = 0;
struct listnode *node;
struct gap_mgmt_group *mg;
for(ALL_LIST_ELEMENTS_RO(group_list,node,mg))
{
vty_out(vty, "group %s %s", mg->group_name, VTY_NEWLINE);
w++;
}
return w;
}
void usermgmt_init()
{
group_list = list_new();
user_list = list_new();
install_node(&user_node, user_config_write);
install_element(CONFIG_NODE, &add_group_cmd);
install_element(CONFIG_NODE, &del_group_cmd);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.