language
large_string | text
string |
---|---|
C | #include "huffman_node.h"
#include "heap.h"
#include <assert.h>
huffmanTree construire_arbre_codes(unsigned int *distrib)
{
Heap* tas=createEmptyHeap();
for (int i = 0; i < 257; i++)
if (distrib[i]!=0)
insert(tas,createLeaf(distrib[i],i));
while(tas->size!=1){
if (tas->size==2)
return addTree(extractMin(tas),extractMin(tas));
insert(tas,addTree(extractMin(tas),extractMin(tas)));
}
return NULL;
}
void creation_table_codes(huffmanTree arbre_codes, Un_code * table_code)
{
//printf("\n %ld\t%d\n",table_code[0].val,table_code[0].val_len );
unsigned long v;
unsigned int lv;
if (arbre_codes==NULL) {
printf("null\n" );
}
else{
if (arbre_codes->left!=NULL)
{
table_code[0].val=2*table_code[0].val;
table_code[0].val_len++;
v=table_code[0].val;
lv=table_code[0].val_len;
creation_table_codes(arbre_codes->left,table_code);
table_code[0].val=v;
table_code[0].val_len=lv;
table_code[0].val=table_code[0].val+1;
creation_table_codes(arbre_codes->right,table_code);
}
else{
table_code[arbre_codes->data].val=table_code[0].val;
table_code[arbre_codes->data].val_len=table_code[0].val_len;
}
}
}
void ecrire_arbre(BAB_FILE *f, huffmanTree arbre_codes)
{
int a=0;
int b=1;
if (arbre_codes!=NULL) {
if (arbre_codes->left==NULL){
bab_fwrite(&a,1, f);
bab_fwrite(&(arbre_codes->data),9,f);
}
else{
bab_fwrite(&b,1, f);
}
ecrire_arbre( f, arbre_codes->left);
ecrire_arbre(f, arbre_codes->right);
}
}
void restaurer_arbre(BAB_FILE *f, huffmanTree *parbre_codes)
{
unsigned long data = 0;
huffmanTree pn = createLeaf(0,0);
*parbre_codes = pn;
if (bab_fread(&data, 1, f) == 0)
{
fprintf(stderr,"Impossible de lire l'arbre de codage\n");
exit(1);
}
if (data & 1)
{
restaurer_arbre(f, &(pn->left));
restaurer_arbre(f, &(pn->right));
}
else
{
pn->data = 0;
bab_fread(&(pn->data), 9, f);
pn->data &= 0x1FF;
pn->left = NULL;
pn->right = NULL;
}
}
unsigned long restaurer_lettre(BAB_FILE *f, huffmanTree pn)
{
huffmanTree tmp=pn;
while (tmp->left!=0){
char c = 0;
bab_fread(&c, 1, f);
c=c&1;
if (c==1)
tmp=tmp->right;
else
tmp=tmp->left;
}
return tmp->data;
}
|
C | #include "graph.h"
/*
* 按行输入 第一行输入 0 2 3 0 0
* 就是说第一个节点和第二个节点边的权重为2
* 第三个之间的边权重为3
* 其他无边
*
*/
GRAPH* init_graph(int num)
{
GRAPH *g = (GRAPH *)malloc(sizeof(GRAPH));
g->node_num = num;
g->edge_num = 0;
g->n = (NODE *)malloc(sizeof(NODE)*num);
int tmp = 0;
for(tmp;tmp < num;tmp++)
{
g->n[tmp].vi = tmp+1;
}
int i = 0;
while(scanf("%d",&tmp) && i < num*num-1)
{
if(tmp != 0)
{
EDGE *p_edge = (EDGE *) malloc(sizeof(EDGE));
p_edge->vj = i%num + 1;
p_edge->weight = tmp;
p_edge->next_vj = NULL;
/*
* i/num 可以表示这是第几行输入
* i%num 表示这是这一行的第几个节点
* +1便于理解*/
if(g->n[i/num].first_arc == NULL)
{
g->n[i/num].first_arc = p_edge;
}
else
{
EDGE *tmp_edge = g->n[i/num].first_arc;
while(tmp_edge->next_vj != NULL)
{
tmp_edge = tmp_edge->next_vj;
}
tmp_edge->next_vj = p_edge;
}
g->edge_num++;
}
i++;
}
return g;
}
void show_graph(GRAPH *g)
{
printf("GRAPH HAS %d nodes\nand has %d edges\n",g->node_num,g->edge_num/2);
int i,j;
int num = g->node_num;
for(i = 0;i < num;i++)
{
EDGE *p_edge;
p_edge = (g->n)[i].first_arc;
printf("%d相连的顶点:",i+1);
while(p_edge != NULL)
{
printf("%d ",p_edge->vj);
p_edge = p_edge->next_vj;
}
printf("\n");
}
}
//标志是否被访问过
//用于小端机器
char *flag;
void DFS(int i,GRAPH *g)
{
printf("%d\n",i+1);
flag[i] = 1;
EDGE *p = g->n[i].first_arc;
while(p != NULL)
{
//因为采用连接表,有可能指向已经访问过的节点,所以要用while循环
//然后再进行递归
//如果采用if(p!= null)的话,p就有可能指向一个visited节点。
//从而flag检测无法通过,无法进行DFS。
//printf("%d\n",g->n[i].first_arc->vj-1);
if(flag[p->vj-1] == 0)
DFS(p->vj-1,g);
p = p->next_vj;
}
}
void DFS_travel(GRAPH *g)
{
flag = (char *) malloc(sizeof(g->node_num));
bzero(flag,g->node_num);
int i=0;
for(i;i < g->node_num;i++)
{
if(flag[i] == 0)
{
DFS(i,g);
}
}
free(flag);
}
/*
* 用list模拟队列*/
void BFS(GRAPH *g)
{
int i=0;
flag = (char *) malloc(sizeof(g->node_num));
bzero(flag,g->node_num);
LIST *queue = init_int(g->node_num);
i = 0;
int j;
for(j= 0;j < g->node_num;j++)
{
if(flag[j] == 0)
{
printf("%d ",g->n[j].vi);
flag[j] = 1;
queue->list_insert(&(g->n[j].vi),queue);
while(( queue->list_get(1,queue)) != 0)
{
i = queue->list_get(1,queue);
i--;
//因为会做为下标 所以减1;
queue->list_delete(1,queue);
EDGE *tmp = g->n[i].first_arc;
while(tmp != NULL)
{
if(flag[tmp->vj - 1] == 0)
{
printf("%d ",tmp->vj);
flag[tmp->vj - 1] = 1;
queue->list_insert(&(tmp->vj),queue);
}
tmp = tmp->next_vj;
}
}
}
}
printf("\n");
}
void DIJ(int index,GRAPH *g)
{
unsigned int MAX = 0xffffffff;
/*
* 表示所有的点都未找到最短路径*/
flag = (char *)malloc(sizeof(g->node_num));
bzero(flag,g->node_num);
/*
* 表示最新加入最短路径集合的点*/
int lastvj = 0;
/*
* path 二维数组代表从index点到各点的最短路径*/
int **path;
path = (int **) malloc(sizeof(int *) * g->node_num);
int i;
for(i = 0;i < g->node_num;i++)
{
path[i] = (int *)malloc(sizeof(int)*g->node_num);
bzero(path[i],g->node_num*sizeof(int));
}
i = index - 1;
flag[i] = 1;
unsigned int *dis = (unsigned int *)malloc(sizeof(int)*g->node_num);
int j = 0;
EDGE *tmp;
tmp = g->n[0].first_arc;
for(i;i < g->node_num;i++)
{
path[i][j] = index - 1;
dis[i] = MAX;
}
dis[0] = 0;
while(tmp != NULL)
{
dis[tmp->vj-1] = tmp->weight;
tmp = tmp->next_vj;
}
unsigned int min = MAX;
for(i = 1;i < g->node_num;i++)
{
for(j = 0;j < g->node_num;j++)
{
if(flag[j] == 0 && min >dis[j])
{
min = dis[j];
lastvj = j;
printf("%d\n",lastvj);
}
}
flag[lastvj] = 1;
for(j = 0;j < g->node_num;j++)
{
unsigned int tmp_dis = MAX;
EDGE *tmp;
tmp = g->n[lastvj].first_arc;
while(tmp != NULL)
{
if(tmp->vj == j)
{
tmp_dis = tmp->weight;
break;
}
tmp = tmp->next_vj;
}
if(flag[j] == 0 && dis[j]-dis[lastvj] > tmp_dis)
{
dis[j] = tmp_dis + dis[lastvj];
}
}
}
for(i=0;i<g->node_num;i++)
{
printf("%u ",dis[i]);
}
printf("\n");
}
int main(int argc,char *argv[])
{
if(argc < 2)
{
printf("usage num\n");
return -1;
}
int num = atoi(argv[1]);
GRAPH *g = init_graph(num);
show_graph(g);
BFS(g);
DIJ(1,g);
}
|
C | /* getlogin.c - an implementation of the `getlogin(3)` library function.
*
* The `getlogin(3)` function returns the username of the user currently
* logged in in the controller terminal of the calling process. Therefore,
* it fails for daemon processes.
*
* This is accomplished by checking the name of the terminal controlling
* the calling process and then reading the `utmp` file for login information.
*
* This function might not work as expected for some terminal emulators.
* Using a virtual console should be enough to test its functionality.
*
* Usage
*
* $ ./getlogin
*
* Author: Renato Mascarenhas Costa
*/
#include <unistd.h>
#include <errno.h>
#include <utmpx.h>
#include <utmp.h>
#include <paths.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef GETLOGIN_LOGIN_MAX
# define GETLOGIN_LOGIN_MAX (256)
#endif
#ifndef GETLOGIN_UTMP_FILE
# define GETLOGIN_UTMP_FILE (_PATH_UTMP)
#endif
static void pexit(const char *fname);
static char *_getlogin(void);
int
main() {
char *login;
if ((login = _getlogin()) == NULL)
pexit("_getlogin");
printf("%s\n", login);
exit(EXIT_SUCCESS);
}
static char *
_getlogin() {
/* find name of the controlling terminal of the calling process */
char *tty;
/* if the controlling terminal name cannot be determined, return a NULL pointer.
* `errno` will have been appropriately set by `ttyname(3)`. */
if ((tty = ttyname(STDIN_FILENO)) == NULL)
return NULL;
/* the static data structure used for all calls to this function */
static char login[GETLOGIN_LOGIN_MAX];
utmpname(GETLOGIN_UTMP_FILE);
/* search for an entry in the utmp file where the ut_line field matches
* that of the controlling terminal name */
errno = 0;
setutxent();
if (errno != 0)
return NULL;
struct utmpx *entry, criteria;
char *line;
/* drop the leading slash, if any */
if (tty[0] == '/')
++tty;
/* remove the `dev/` prefix from the ttyname, if existent */
if ((line = strchr(tty, '/')) == NULL)
line = tty;
else
/* dev/pts/0 becomes pts/0 */
++line;
strncpy(criteria.ut_line, line, __UT_LINESIZE);
if ((entry = getutxline(&criteria)) == NULL)
return NULL;
strncpy(login, entry->ut_user, GETLOGIN_LOGIN_MAX);
/* finish the reading of the utmp file */
errno = 0;
endutxent();
if (errno != 0)
return NULL;
return login;
}
static void
pexit(const char *fname) {
perror(fname);
exit(EXIT_FAILURE);
}
|
C | #include <stdio.h>
#include <stdbool.h>
#define STACK_SIZE 100
/* external variables */
char contents[STACK_SIZE];
int top = 0;
bool underflow = false, overflow = false;
void make_empty(void);
bool is_empty(void);
bool is_full(void);
void push(char ch);
char pop(void);
void stack_overflow(void);
void stack_underflow(void);
int main(void)
{
char brace;
bool validity = true, open;
printf("Enter parentheses and/or braces: ");
for(;;)
{
open = true;
brace = getchar();
switch (brace)
{
case '(': case '{': case '[':
open = true;
push(brace);
break;
case ')':
open = false;
brace = '(';
break;
case '}':
open = false;
brace = '{';
break;
case ']':
open = false;
brace = '[';
break;
case '\n':
break;
default:
validity = false;
break;
}
if (open == false)
if (brace != pop())
validity = false;
if (validity == false)
break;
if (brace == '\n')
break;
if (underflow)
break;
if (overflow)
break;
}
if (overflow)
printf("Stack overflow\n");
else if (is_empty() && (underflow == false) && (validity == true))
{
printf("Parentheses/braces are nested properly\n");
}
else
printf("Parentheses/braces aren't nested properly\n");
return 0;
}
void make_empty(void)
{
top = 0;
}
bool is_empty(void)
{
return top == 0;
}
bool is_full(void)
{
return top == STACK_SIZE;
}
void push(char ch)
{
if (is_full())
stack_overflow();
else
contents[top++] = ch;
}
char pop(void)
{
if (is_empty())
stack_underflow();
else
return contents[--top];
}
void stack_overflow(void)
{
overflow = true;
}
void stack_underflow(void)
{
underflow = true;
}
|
C | /** Demonstration of how to use a bit field, accessing just selected bits in a larger
value, as if they are a little integer. */
#include <stdio.h>
#include <stdlib.h>
// Increment just bits 8 - 11, returning the resut, with the
// remaining bits left unchanged.
unsigned short increment8to11( unsigned short s )
{
// Extract the contents of the bit field, and move it into the low-order bits.
unsigned short bitField = ( s & 0x0F00 ) >> 8;
// Add one our copy of the bit field's value
bitField++;
// Get ready to put the updated value of the bit field back. Clear out the contents
// of the bit field.
s &= 0xF0FF;
// Shift the updated bit field back to where it goes, mask of any remaining bits (in
// case there was some overflow) and or the result back into the original value.
s |= ( ( bitField << 8 ) & 0x0F00 );
// We're done, reutrn the result.
return s;
}
int main() {
// Make up a value containing some random-looking bits.
unsigned short s = 0xA2B3;
// Show how this works by incrementing just this bit field a bunch of times.
for ( int i = 0; i < 16; i++ ) {
s = increment8to11( s );
printf( "%04X\n", s );
}
return EXIT_SUCCESS;
}
|
C | #include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<string.h>
#define SHMSZ 100
int main()
{
int shmid;
key_t key;
key=1234;
char *shm,*s;
if((shmid=shmget(key,SHMSZ,IPC_CREAT|0660))<0)
{
perror("shget");
exit(1);
}
//attach the process2 to this shm
if((shm=shmat(shmid,NULL,0))==(char*)-1)
{
perror("shget");
exit(1);
}
s=shm;
//read from shm
char *amt;
int amount,debit;
amount=atoi(s);
printf("The amount in the atm is:%d",amount);
if(amount>20)
{
printf("Enter the amount to debit:");
//read from terminal
scanf("%d",&debit);
amount=amount-debit;
printf("the amount remaining is %d",amount);
//stor in shm
printf("Enter amount left");
fgets(s,40,stdin);
}
/*for(s=shm;*s!='\0';s++)
{
putchar(*s);
}
*/
return(0);
}
|
C | #include <stdio.h>
#include <stdlib.h>
struct node_t {
int data;
struct node_t *next;
};
struct list_t {
struct node_t *head;
};
struct list_t init_list() {
struct list_t result = { NULL };
return result;
}
struct node_t* init_node(int item) {
struct node_t *result = malloc(
sizeof(struct node_t));
result->data = item;
result->next = NULL;
return result;
}
void insert(struct list_t* list, int item) {
struct node_t *new_node = init_node(item);
new_node->next = list->head;
list->head = new_node;
}
int remove_list(struct list_t *list) {
if(list->head == NULL) {
return -1;
}
int result = list->head->data;
struct node_t *tmp = list->head->next;
free(list->head);
list->head = tmp;
return result;
}
void destroy_list(struct list_t *list) {
while(list->head) {
remove_list(list);
}
}
int main() {
struct list_t list = init_list();
for(int i = 0; i < 3; i++) {
insert(&list, i+1);
}
// for(int i = 0; i < 3; i++) {
// printf("%d ", remove_list(&list));
//}
//printf("\n");
destroy_list(&list);
return 0;
}
|
C | #include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<pthread.h>
void *thread_run(void *arg)
{
while(1){
printf("I am %s, pid : %d ,my thread id is %p\n",(char*)arg,getpid(),pthread_self());
sleep(1);
int a = 1 / 0;
}
}
int main()
{
pthread_t tid;
//你新创建的线程id就会放在tid中
pthread_create(&tid,NULL,thread_run,(void*)"thread 1");
while(1){
printf("I am main thread id : %p,new thread : %p, pid : %d\n",pthread_self(),tid,getpid());
sleep(2);
}
return 0;
}
|
C | /*********************
* TCP SOCKET TEST 3
* ******************/
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <math.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main(int argc, char *argv[])
{
if(argc < 7) {
printf("\nUsage: ./receiver <num_sender> <receiver_port> <packet_size_in_bytes> <packet_number> <control_port> <ack_port>\n\n");
exit(1);
}
int num_sender = atoi(argv[1]); // how many people are sending us data?
int port[num_sender]; // ports array
int sock[num_sender]; // socket descriptor array
int first_port = atoi(argv[2]); // first port for the server
int packet_size = atoi(argv[3]); // how many KB is a packet?
int true = 1, bytes_received;
long message_size = packet_size;
long total_bytes_recv = 0;
char recv_data[message_size];
int packet_number = atoi(argv[4]); // how many packets are we going to receive?
int ack_port = atoi(argv[6]); /* this is the port we're sending the ACK to at the end of the transmission */
struct sockaddr_in this_addr[num_sender], sender_addr[num_sender]; // array for server and client sockets
int sin_size;
int connected[num_sender]; // connection descriptor array
// this is for the timer
struct timeval tv;
double receive_start, receive_end;
int k, j, rc;
for (k = 0; k < num_sender; k++) {
// socket creation
if ((sock[k] = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("Socket");
exit(1);
}
// socket options setting
if (setsockopt(sock[k], SOL_SOCKET, SO_REUSEADDR, &true,sizeof(int)) == -1) {
perror("Setsockopt SO_REUSEADDR");
exit(1);
}
if (setsockopt(sock[k], IPPROTO_TCP, TCP_NODELAY, &true, sizeof(int)) == -1)
{
perror("Setsockopt TCP_NODELAY");
exit(1);
}
/*
rc = ioctl(sock[k], FIONBIO, &true);
if (rc < 0)
{
perror("ioctl() failed");
close(sock[k]);
exit(-1);
}
*/
}
for (k = 0; k < num_sender; k++) {
// sockaddr settings
this_addr[k].sin_family = AF_INET;
this_addr[k].sin_port = htons(first_port + k);
this_addr[k].sin_addr.s_addr = INADDR_ANY;
bzero(&(this_addr[k].sin_zero),8);
// socket binding
if (bind(sock[k], (struct sockaddr *)&this_addr[k], sizeof(struct sockaddr)) == -1) {
perror("Unable to bind");
exit(1);
}
// listening on socket
if(listen(sock[k], 1) == -1) {
perror("Listen");
exit(1);
}
//printf("Listening on port %d\n", (first_port + k));
}
sin_size = sizeof(struct sockaddr_in);
double diff_time, total_time = 0, accept_start, accept_end, total_accept = 0;
int control_port = atoi(argv[5]); /* DEFAULT control UDP port to receive the
* "start" command */
int cmd_len = 256; /* max length of the command line received via the
* control port */
/* Create the socket */
int ctrl_socket = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP );
if ( ctrl_socket < 0)
perror( "ERROR opening control socket" );
struct sockaddr_in ctrl_address;
bzero( (char *) &ctrl_address, sizeof( ctrl_address ) );
ctrl_address.sin_family = AF_INET;
ctrl_address.sin_addr.s_addr = INADDR_ANY;
ctrl_address.sin_port = htons( control_port );
//P_DEBUG( 1, "LISTEN for START on port " << ntohs( ctrl_address.sin_port ) << endl );
socklen_t tmplen = sizeof( ctrl_address );
/* Bind the socket */
int bind_error = bind( ctrl_socket, (struct sockaddr *) &ctrl_address, tmplen );
if ( bind_error < 0 )
//ERRNO( "on binding control socket" << endl );
perror("Bind");
/* Listen, accept, and go on */
listen( ctrl_socket, 5 );
printf("Listening on control port %d\n", control_port);
char command[ cmd_len ];
int ctrl_recv_size = recvfrom( ctrl_socket, &command, cmd_len, 0, (struct sockaddr *) &ctrl_address, &tmplen );
close( ctrl_socket );
// accepting incoming connections and measuring the time
gettimeofday(&tv, NULL);
accept_start = tv.tv_sec * 1E6 + tv.tv_usec;
for (k = 0; k < num_sender; k++) {
connected[k] = accept(sock[k], (struct sockaddr *)&sender_addr[k], &sin_size);
//printf("Received connection from %d\n", k);
}
gettimeofday(&tv, NULL);
accept_end = tv.tv_sec * 1E6 + tv.tv_usec;
total_accept = accept_end - accept_start;
// receiving data and measuring the time
int partial_bytes;
//double partial_time;
gettimeofday(&tv, NULL);
receive_start = tv.tv_sec * 1E6 + tv.tv_usec;
for (k = 0; k < packet_number; k++) {
for (j = 0; j < num_sender; j++) {
bytes_received = recv(connected[j], recv_data, message_size, MSG_WAITALL);
total_bytes_recv += bytes_received;
//printf("Partial received %d bytes\n", bytes_received);
}
}
gettimeofday(&tv, NULL);
receive_end = tv.tv_sec * 1E6 + tv.tv_usec;
total_time = receive_end - receive_start;
/* sending to each sender the ACK at the end of the transmission */
int ack_sock[num_sender];
char ack[] = "ACK";
int i;
for (i = 0; i < num_sender; i++) {
if ((ack_sock[i] = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("Socket");
exit(1);
}
if (setsockopt(ack_sock[i], SOL_SOCKET, SO_REUSEADDR, &true, sizeof(int)) == -1) {
perror("Setsockopt");
exit(1);
}
if (setsockopt(ack_sock[i], IPPROTO_TCP, TCP_NODELAY, &true, sizeof(int)) == -1)
{
perror("Setsockopt TCP_NODELAY");
exit(1);
}
sender_addr[i].sin_port = htons(ack_port);
if (connect(ack_sock[i], (struct sockaddr *)&sender_addr[i], sizeof(sender_addr[i])) == -1)
{
perror("Connect");
exit(1);
}
send(ack_sock[i], ack, 3, 0);
printf("ACK sent to sender number %d\n", i);
}
// closing sockets
for (k = 0; k < num_sender; k++) {
close(connected[k]);
close(ack_sock[k]);
}
double band = (total_bytes_recv * 8 * 1E6) / (total_time * pow(2, 30));
printf("Total accept() time: %.0f usec\n", total_accept);
printf("Total bytes received %ld in %.f usec\n", total_bytes_recv, total_time);
printf("Bandwidth Receiver: %.2f Gb/s\n", band);
printf("\n");
fflush(stdout);
return 0;
}
|
C | #ifndef __JSON_H__
#define __JSON_H__
/**
* \file json.h
* \brief Module contenant les primitives et les structures permettant l'écriture et la lecture de fichier JSON.
* \author GALBRUN Tibane
* \version 0.3
* \date 5 Mars 2019
*/
#include <stdio.h>
#include <stdlib.h>
#include <erreur.h>
/* Primitives de création, d'ouverture, de fermeture et de suppression */
/* Création et/ou Ouverture d'un fichier JSON /
Utilisation : FILE * file = open_json("dossier/JSON", "name", "mode") */
FILE * open_json (char * dossier, char * name, char * mode);
/* Suppression d'un fichier JSON /
Utilisation : del_json("dossier/JSON", "name") */
t_erreur del_json (char * dossier, char * name);
/* Primitives d'écriture */
/* Ecriture dans un fichier JSON d'une valeur avec sa clé /
Utilisation : write_json(file, cle, valeur, type_de_la_valeur) */
t_erreur write_json (FILE * file, char * key, void * value, char * value_type);
/* Ouverture d'un nouvel objet dans un fichier JSON /
Utilisation : open_json_obj(file) */
t_erreur open_json_obj (FILE * file);
/* Fermeture d'un objet dans un fichier JSON /
Utilisation : close_json_obj(file) */
t_erreur close_json_obj (FILE * file);
/* Primitives de lecture */
/* Extraction d'un objet dans un fichier JSON /
Utilisation : extract_json_obj(file, &obj) */
t_erreur extract_json_obj (FILE * file, char ** obj);
/* Lit le contenu d'un objet /
Utilisation : read_json_obj(obj,cle,valeur,type_de_la_valeur)
type_de_la_valeur = [d,s,f] */
t_erreur read_json_obj (char * obj, char * key, void * value, char * value_type);
/* Remet au début du fichier */
t_erreur fstart (FILE * file);
#endif |
C | //Program for DFS using C
#include<stdio.h>
#include<stdlib.h>
//Array to store visited nodes
int v[7]={0,0,0,0,0,0,0}; //7 denotes the no. of vertex
void dfs(int arr[][7],int cur)
{
//Print the visited node
printf("\n%d",cur+1);
//Update visited count
v[cur]=1;
//Find adjacent unvisited nodes
for(int i=0;i<7;i++)
{
//Check adjacency and if unvisited (0 value on v array)
if(arr[cur][i]==1 && v[i]==0)
{
//Go to that vertex from current
dfs(arr,i);
}
}
//Trace back
return;
}
int main(void)
{
//The graph as input
int arr[][7]={{0,1,1,0,0,0,0},{1,0,0,1,1,0,0},{1,0,0,0,1,0,0},{0,1,0,0,1,1,0},{0,1,1,1,0,1,0},{0,0,0,1,1,0,0},{0,0,0,0,0,0,0}};
printf("\nVertex are of the order:");
//We need a for-loop to iterate through all vertex individually
//Since, DFS cannot work for unconnected graphs
for(int i=0;i<7;i++)
{
if(v[i]==0) //If Unvisited, then only continue
dfs(arr,i);
}
} |
C | #include "arvbb.h"
Arv* arvore_cria(void) {
return NULL;
}
Arv* arvore_insere(Arv* a, tipoItem v) {
if (arvore_busca(a, v) == 1)
return a;
if (a == NULL) {
a = (Arv*) malloc(sizeof (Arv));
strcpy(a->palavra.nome, v.nome);
a->esq = a->dir = NULL;
} else if (strcmp(v.nome, a->palavra.nome) < 0)
a->esq = arvore_insere(a->esq, v);
else /* v < a->chave*/
a-> dir = arvore_insere(a->dir, v);
return a;
}
void arvore_imprimePreEsq(Arv* a) {
if (a != NULL) {
printf("%s ", a->palavra.nome);
arvore_imprimePreEsq(a->esq);
arvore_imprimePreEsq(a->dir);
}
}
void arvore_imprimePreDir(Arv* a) {
if (a != NULL) {
printf("%s ", a->palavra.nome);
arvore_imprimePreDir(a->dir);
arvore_imprimePreDir(a->esq);
}
}
void arvore_imprimeCentEsq(Arv* a) {
if (a != NULL) {
arvore_imprimeCentEsq(a->esq);
printf("%s ", a->palavra.nome);
arvore_imprimeCentEsq(a->dir);
}
}
void arvore_imprimeCentDir(Arv* a) {
if (a != NULL) {
arvore_imprimeCentDir(a->dir);
printf("%s ", a->palavra.nome);
arvore_imprimeCentDir(a->esq);
}
}
void arvore_imprimePosEsq(Arv* a) {
if (a != NULL) {
arvore_imprimePosEsq(a->esq);
arvore_imprimePosEsq(a->dir);
printf("%s ", a->palavra.nome);
}
}
void arvore_imprimePosDir(Arv* a) {
if (a != NULL) {
arvore_imprimePosDir(a->dir);
arvore_imprimePosDir(a->esq);
printf("%s ", a->palavra.nome);
}
}
int arvore_busca(Arv* r, tipoItem v) {
if (r == NULL)
return 0;
else if (strcmp(r->palavra.nome, v.nome) > 0)
return arvore_busca(r->esq, v);
else if (strcmp(r->palavra.nome, v.nome) < 0)
return arvore_busca(r->dir, v);
else
return 1;
}
int buscabb(Arv* r, char *nome) {
printf("entrou na funcao de busca\n\n");
if (r == NULL)
return 0;
else if (strcmp(r->palavra.nome, nome) > 0)
return buscabb(r->esq, nome);
else if (strcmp(r->palavra.nome, nome) < 0)
return buscabb(r->dir, nome);
else
return 1;
}
|
C | #include "stdio.h"
void main()
{
int a,i,b,c[10]={10,20,30,40,50};
printf("\nEnter number position");
scanf("%d",&a);
printf("\nEnter number to insert");
scanf("%d",&b);
for(i=4;i>=a-1;i--)
{
c[i+1]=c[i];
}
c[a-1]=b;
printf("All numbers are\n");
for(i=0;i<6;i++)
{
printf("%d\t",c[i]);
}
}
|
C | #include <stdio.h>
#include "stack.h"
#include <stdlib.h>
#include <assert.h>
int empty( struct node** top)
{
return(*top== NULL); // jesli pusta true
}
void push(char i, struct node ** top)
{
struct node *new_node = malloc (sizeof (struct node));
new_node->val=i;
new_node->next=*top;
*top=new_node;
}
int pop(struct node ** top)
{
int retval = -1;
struct node * next_node = NULL;
if (*top == NULL) {
return -1;
}
next_node = (*top)->next;
retval = (*top)->val;
free(*top);
*top = next_node;
return retval;
}
void print( struct node *top)
{
struct node* tmp=top;
printf("Lista : \n");
while( !(tmp->next==NULL))
{
printf("%c \n",tmp->val);
tmp=tmp->next;
}
}
int head_val( struct node * top )
{
return top->val;
}
void destroy( struct node ** top )
{
struct node* tmp=(*top)->next;
while( !((*top)->next==NULL))
{
tmp=(*top)->next;
free(*top);
(*top)=tmp;
}
}
int ifmatch(char ch1, char ch2)
{
if (ch1 == '(' && ch2 == ')')
return 1;
else
return 0;
}
int check_bracket(char string[])
{
int i = 0;
struct node *stack = malloc(sizeof(struct node));
stack =NULL;
while (string[i])
{
if (string[i] == '(')
{
push( string[i], & stack );
}
if (string[i] == ')')
{
if (stack == NULL)
return 0;
else if ( !ifmatch(pop(&stack), string[i]) )
return 0;
}
i++;
}
return empty(&stack);
}
|
C | #include <stdio.h>
int main(int argc, char** argv)
{
printf("the char size is %ld\n",sizeof(char));
printf("the short size is %ld\n",sizeof(short));
printf("the int size is %ld\n",sizeof(int));
printf("the long size is %ld\n",sizeof(long));
printf("the float size is %ld\n",sizeof(float));
printf("the double size is %ld\n",sizeof(double));
printf("the pointer type size is %ld\n",sizeof(int*));
}
|
C | #include <stdio.h>
#include <sys/stat.h>
#include <string.h>
#include <dirent.h>
//#define NULL 0
#define PROC_DEV_PATH "/proc/dev"
int main(int argc, char ** argv)
{
DIR *pDir;
struct dirent *pEnt;
struct stat fstat;
pDir = opendir (PROC_DEV_PATH);
if(!pDir) {
fprintf(stdout, "Error to read proc/dev path\n");
}
while (pDir) {
if ( (pEnt = readdir (pDir)) != NULL) {
fprintf(stdout, "System dev: %s\n", pEnt->d_name);
}
}
return 0;
}
|
C | #include<stdio.h>
#include<string.h>
void main()
{
char b[100],a[100];
printf("Enter the string 1");
scanf("%s\n",&a);
printf("\nEnter the string 2");
scanf("\n%s",&b);
printf("\n%s%s",a,b);
}
|
C | #include <stdio.h>
#include <stdlib.h>
int main( void ){
// fprintf( stdout, "Hello, World %p\n", stdout );
int size = -13 * sizeof( char );
void* hello = malloc( size );
fprintf( stdout, "%p %p\n", &hello, hello );
free( hello );
return 0;
}
|
C | #include <stdio.h>
#include "kiss_fft.h"
#include "kiss_fftr.h"
kiss_fft_cpx *copycpx(float *mat, int nframe) {
int i;
kiss_fft_cpx *mat2;
mat2 = (kiss_fft_cpx *) KISS_FFT_MALLOC(sizeof(kiss_fft_cpx) * nframe);
kiss_fft_scalar zero;
memset(&zero, 0, sizeof(zero));
for (i = 0; i < nframe; i++) {
mat2[i].r = mat[i];
mat2[i].i = zero;
}
return mat2;
}
int main(void) {
int i, size = 12;
int isInverse = 1;
float buf[size];
float array[] = {0.1, 0.3, 0.1, 0.4, 0.5, 0, 0.8, 0.7, 0.8, 0.6, 0.1, 0};
kiss_fft_cpx out_cpx[size], out[size], *cpx_buf;
kiss_fftr_cfg fft = kiss_fftr_alloc(size * 2, 0, 0, 0);
kiss_fftr_cfg ifft = kiss_fftr_alloc(size * 2, isInverse, 0, 0);
cpx_buf = copycpx(array, size);
kiss_fftr(fft, (kiss_fft_scalar *) cpx_buf, out_cpx);
kiss_fftri(ifft, out_cpx, (kiss_fft_scalar *) out);
printf("Input: \tOutput:\n");
for (i = 0; i < size; i++) {
buf[i] = (out[i].r) / (size * 2);
// buf[i] = (out_cpx[i].r) / (size * 2);
printf("%f\t%f\n", array[i], buf[i]);
}
kiss_fft_cleanup();
free(fft);
free(ifft);
return 0;
} |
C | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
static bool hash[101]={false};
struct Node {
int data;
struct Node* next;
};
struct Queue {
struct Node *front;
struct Node *rear;
struct Node *curr;
int capacity,size;
};
struct Node* newNode(int value)
{
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = value;
temp->next = NULL;
return temp;
}
void printList(struct Queue* q)
{
struct Node* temp=q->front;
while(temp!=NULL)
{
printf("%d",temp->data," ");
temp=temp->next;
}
}
void printHash()
{
printf(" ");
for(int i=0;i<7;i++)
{
printf("%d",hash[i]);
}
printf("\n");
}
void moveToBottom(struct Queue *q,int value)
{
struct Node *temp=q->front;
struct Node * prev=NULL;
while(temp!=NULL)
{
if(temp->data==value) break;
prev=temp;
temp=temp->next;
}
prev->next=temp->next;
q->rear->next=temp;
q->rear=temp;
q->rear->next=NULL;
}
void enQueue(struct Queue* q, int value,int frame_size)
{
if(hash[value]) moveToBottom(q,value);
else if(q->size==0)
{
q->front=newNode(value);
q->rear=q->front;
q->size=q->size+1;
}
else if(q->size<=frame_size)
{
struct Node* temp = newNode(value);
q->rear->next=temp;
q->rear=temp;
q->size=q->size+1;
}
else
{
hash[q->front->data]=false;
q->rear->next=q->front;
q->front->data=value;
q->rear=q->rear->next;
q->front=q->front->next;
q->rear->next=NULL;
}
hash[value]=true;
}
struct Queue* createQueue(int frame_size)
{
struct Queue* q = (struct Queue*)malloc(sizeof(struct Queue));
q->front = q->rear = NULL;
q->size=0;
q->capacity=frame_size;
return q;
}
void LRU(int *PageList,int n)
{
int hits=0;
struct Queue* queue = createQueue(5);
for(int i=0;i<n;i++)
{
if(hash[PageList[i]]==1)
{
hits++;
}
enQueue(queue,PageList[i],5);
}
printf("%d",hits);
}
int main() {
int pagelist[]={7,0,1,2,0,3,0,4,2,3,0,3,2};
LRU(pagelist,13);
return 0;
} |
C | #include "image.h"
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int arg_count, char **args)
{
if(arg_count == 4)
{
pid_t wpid;
int status = 0;
struct image input = make_image_from_file(args[1]);
struct image output = make_image(input.type, input.row_count, input.column_count, input.max_value);
FILE * file1 = tmpfile();
FILE * file2 = tmpfile();
FILE * file3 = tmpfile();
int child = fork();
if(!child){//fils1
blur_image_layer(&input, &output, strtoul(args[3], 0, 0), 0);
write_image_to_stream(&output, file1);
fseek(file1,0,SEEK_SET);
clear_image(&input);
clear_image(&output);
}else{
int child2 = fork();
if(!child2){//fils2
blur_image_layer(&input, &output, strtoul(args[3], 0, 0), 1);
write_image_to_stream(&output, file2);
fseek(file2,0,SEEK_SET);
clear_image(&input);
clear_image(&output);
}else{
int child3 = fork();
if(!child3){//fils3
blur_image_layer(&input, &output, strtoul(args[3], 0, 0), 2);
write_image_to_stream(&output, file3);
fseek(file3,0,SEEK_SET);
clear_image(&input);
clear_image(&output);
}else{
//pere
while((wpid = wait(&status)) > 0);
struct image input1 = make_image_from_stream(file1);
copy_image_layer(&input1,&output,0);
clear_image(&input1);
input1 = make_image_from_stream(file2);
copy_image_layer(&input1,&output,1);
clear_image(&input1);
input1 = make_image_from_stream(file3);
copy_image_layer(&input1,&output,2);
clear_image(&input1);
//dup2
//exec
write_image_to_file(&output,args[2]);
}
}
}
}
else
{
fprintf(stderr, "Essaie plutôt : %s input.ppm output.ppm 10\n", args[0]);
}
}
|
C | #include "serial.h"
#include "schedule.h"
#include "state.h"
#include <timer.h>
#include <peripherals\switches\switch.h>
#include <peripherals\potentiometer\pot.h>
#include <peripherals\rgb_led\rgb_led.h>
#include <shell.h>
void init_shell();
void check_peripherals();
void init_peripherals();
int main(void) {
init_timer();
init_peripherals();
init_shell();
while(1) {
// read serial and pass to shell
if(serial_available())
shell_receive_char(serial_getc());
if(state_get() == STOPPED)
continue;
/*
* Check for actions and events then push those
* events onto the state queue.
*/
schedule_update();
check_peripherals();
// process all events pushed onto the queue
state_update();
}
}
void check_peripherals() {
pot_update();
led_update();
switch_update();
}
void init_peripherals() {
USART_Init();
init_rgb_led();
init_switch();
}
void init_shell() {
// Configure shell
sShellImpl shell_impl = {
.send_char = serial_putc,
};
shell_boot(&shell_impl);
} |
C | #include "computer.h"
#include "online.c"
///Function Name : selec
///Description : To select mode of shopping
///Input Params : start,order,soft,wake
///Return : void
void selec(COMPUTER* start,ORDER* order,SOFTWARE* soft,QUEUE* wake)
{
int choice,chh;
system("cls");
printf(" -------------------------------------------------------------------------\n");
printf(" WELCOME TO \n");
printf(" *** TECH CLOUD *** \n");
printf(" THE ULTIMATE PLACE TO FIND THE HARDWARE AND SOFTWARE COMPUTER SERVICES \n");
printf(" -------------------------------------------------------------------------\n\n");
///if user is a customer
if(u==1)
choice=0;
///if user is a owner
if(u==2)
{
printf(" 1-> EXPORT\n");
printf(" 2-> IMPORT\n");
printf(" 3-> Exit\n\n ");
scanf("%d",&choice);
}
switch(choice)
{
case 0: if (u==2)
system("cls");
printf(" **************************** SALES SECTION ******************************\n\n");
printf(" 1-> SPOT SHOPPING\n");
printf(" 2-> ONLINE SHOPPING\n");
printf(" 3-> EXIT\n\n ");
printf("\n Enter your choice\n ");
scanf("%d",&chh);
switch(chh)
{
case 1: printf("\n Entering Spot Shopping!!!!\n");
printf(" To continue, enter any key...");
getch();
spot(start,order,soft,wake);
break;
case 2: printf("\n Entering Online Shopping!!!!\n");
printf(" To continue, enter any key...");
getch();
online(start,order,soft,wake);
break;
case 3: printf("\n Exiting The Shopping\n");
printf(" To continue, enter any key...");
getch();
printf("\a\a");
MessageBox(0, "Thank You !! Visit Again! :)", "TECH CLOUD", MB_OK);
printf("\n\n");
exit(0);
break;
default:
printf("\a\a");
MessageBox(0, "Invalid Choice !!", "TECH CLOUD", MB_OK);
break;
}
break;
case 1 : export(start,soft);
break;
case 2 : import(start,soft);
break;
case 3 : printf("\a\a");
MessageBox(0, "Thank You!! VISIT AGAIN!! :)", "TECH CLOUD", MB_OK);
exit(0);
break;
default :
printf("\a\a");
MessageBox(0, "Invalid Choice !!", "TECH CLOUD", MB_OK);
break;
}
selec(start,order,soft,wake);
}
///Function Name : online
///Description : In online section to select types of products
///Input Parms : start,order,acc,wake
///Return : void
void online(COMPUTER* start,ORDER* order,SOFTWARE* soft,QUEUE* wake)
{
int choice=0;
char key[10];
system("cls");
printf(" -------------------------------------------------------------------------\n");
printf(" ONLINE SHOPPING SECTION \n");
printf(" -------------------------------------------------------------------------\n\n");
printf(" 1-> HARDWARE COMPUTER SERVICES\n");
printf(" 2-> SOFTWARE COMPUTER SERVICES\n");
printf(" 3-> VIEW THE ORDERS\n");
printf(" 4-> SERVE THE ORDERED ITEMS\n");
printf(" 5-> SEARCH ITEMS BY KEYWORD\n");
printf(" 6-> EXIT\n ");
printf("\n Enter your choice\n ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\n HARDWARE COMPUTER SERVICES SECTION!!!\n");
printf(" To continue, enter any key...\n ");
getch();
wake=online_hardwr(start,order,soft,wake);
break;
case 2:
printf("\n SOFTWARE COMPUTER SERVICES SECTION!!!\n");
printf(" To continue, enter any key...\n ");
getch();
wake=online_softwr(soft,order,start,wake);
break;
case 3:
display(wake);
break;
case 4:
wake=serve(wake);
online(start,order,soft,wake);
break;
case 5: system("cls");
printf("\n-----------------------------------------------------------------------------");
printf("\n **** WELCOME TO SEARCH ENGINE **** ");
printf("\n-----------------------------------------------------------------------------\n");
printf(" What do u want to Search?\n\n");
printf(" * Enter the keyword in CAPITAL LETTERS :\n ");
scanf("%s",key);
search(key,start,soft);
break;
case 6:
printf(" Exiting From Online Shopping!!!\n");
printf(" To continue, enter any key...\n ");
getch();
MessageBox(0, "Successfully Exited from Online Section", "TECH CLOUD", MB_OK);
selec(start,order,soft,wake);
break;
default:
MessageBox(0, "Invalid Choice !!", "TECH CLOUD", MB_OK);
break;
}
online(start,order,soft,wake);
}
///Function Name : spot
///Description : In spot section to select type of products
///Input Params : start,order,soft,wake
///Return : void
void spot(COMPUTER* start,ORDER* order,SOFTWARE* soft,QUEUE* wake)
{
char key[10];
while(1)
{
int choice=0;
system("cls");
printf("-------------------------------------------------------------------------\n");
printf(" WELCOME TO SPOT SHOPPING SECTION \n");
printf("-------------------------------------------------------------------------\n\n");
printf(" 1-> HARDWARE COMPUTER SERVICES\n");
printf(" 2-> SOFTWARE COMPUTER SERVICES\n");
printf(" 3-> YOUR CART\n");
printf(" 4-> SEARCH ITEMS BY KEYWORD\n");
printf(" 5-> EXIT\n ");
printf("\n Enter your choice\n ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\n HARDWARE COMPUTER SERVICES SECTION!!!\n");
printf(" To continue, enter any key...\n ");
getch();
hardware_sec(start,order,soft,wake);
break;
case 2:
printf("\n SOFTWARE COMPUTER SERVICES SECTION!!!\n");
printf(" To continue, enter any key...\n ");
getch();
software_sec(soft,order,start,wake);
break;
case 3 :printf("\n Entering into your cart .......\n");
printf(" To continue, enter any key...\n ");
getch();
t=1;
buy(order,start,soft,wake);
break;
case 4: system("cls");
printf("\n-----------------------------------------------------------------------------");
printf("\n **** WELCOME TO SEARCH ENGINE **** ");
printf("\n-----------------------------------------------------------------------------\n");
printf(" What do u want to Search\n\n");
printf(" * Enter the keyword in CAPITAL LETERS :\n ");
scanf("%s",key);
search(key,start,soft);
break;
case 5:
printf("\n Exiting From Spot Shopping!!!\n");
printf(" To continue, enter any key...\n ");
getch();
MessageBox(0, "Successfully Exited from Spot Shopping Section", "TECH CLOUD", MB_OK);
selec(start,order,soft,wake);
break;
default:
MessageBox(0, "Invalid Entry", "TECH CLOUD", MB_OK);
break;
}
}
}
///Function Name : hardware_sec
///Description : Function Provides different hardware products and you can order it in 'spot shopping'
///Input Params : start,order,soft,wake
///Return : void
void hardware_sec(COMPUTER* start,ORDER* order,SOFTWARE* soft,QUEUE* wake)
{
int choice=0,ch1=0,op=0,ch2=0;
int i=1;
system("cls");
printf("-------------------------------------------------------------------\n");
printf(" HARDWARE SECTION \n");
printf("-------------------------------------------------------------------\n\n");
printf(" Search for...\n\n");
printf(" 1->LAPTOPS\n");
printf(" 2->PENDRIVES\n");
printf(" 3->HARDDISKS\n\n ");
printf("\n Enter your choice\n ");
scanf("%d",&ch1);
if (ch1==1)
{
system("cls");
printf(" -------------------------------------------------------------------\n");
printf(" LAPTOPS SECTION \n");
printf(" -------------------------------------------------------------------\n\n");
printf("\n Latest laptop models are here......\n\n");
printf(" Search based on...\n\n");
printf(" 1-> BRAND\n");
printf(" 2-> PROCESSOR NAME\n");
printf(" 3-> PRICE\n");
printf(" 4-> Exit\n\n ");
printf("\n Enter your choice\n ");
scanf("%d",&choice);
if(choice==1)
{
system("cls");
printf("\n Search for...\n\n");
printf(" LENOVO\n ACER\n HP\n DELL\n ALIENWARE\n\n");
COMPUTER* temp;
temp=start;
char brand[20];
int i=1,flag=0;
printf(" Enter the Brand Name\n ");
scanf("%s",brand);
system("cls");
while(temp!=NULL)
{
if(strcmpi(temp->name,brand)==0)
{
printf("\n Option :%d\n\n NAME\t\t : %s \n Processor_name\t : %s CORE %s %s\n HDD_capacity\t : %s",i,temp->name,temp->brand,temp->processor_name,temp->processor_generation,temp-> HDD_capacity);
printf("\n Ram\t\t : %s \n Graphics\t : %s\n Operating System: %s\n PRICE\t\t :Rs %f\n\n",temp->ram,temp->Graphics,temp->Operating_System,temp->price);
flag=1;
}
temp=temp->next;
i++;
}
if (flag==0)
{
MessageBox(0, "Invalid choice", "TECH CLOUD", MB_OK);
hardware_sec(start,order,soft,wake);
}
}
else if(choice==2)
{
system("cls");
printf("\n Search for...\n\n ");
printf("\n i3\n i5\n i7\n\n");
COMPUTER* temp;
temp=start;
char processor_name[10];
int i=1,flag=0;
printf(" Enter processor_name\n ");
scanf("%s",processor_name);
system("cls");
while(temp!=NULL)
{
if(strcmpi(temp->processor_name,processor_name)==0)
{
printf("\n Option :%d\n\n NAME\t\t : %s \n Processor_name\t : %s CORE %s %s\n HDD_capacity\t : %s",i,temp->name,temp->brand,temp->processor_name,temp->processor_generation,temp-> HDD_capacity);
printf("\n Ram\t\t : %s \n Graphics\t : %s\n Operating System: %s\n PRICE\t\t : Rs %f\n\n",temp->ram,temp->Graphics,temp->Operating_System,temp->price);
flag=1;
}
temp=temp->next;
i++;
}
if (flag==0)
{
MessageBox(0, "Invalid choice", "TECH CLOUD", MB_OK);
hardware_sec(start,order,soft,wake);
}
}
else if(choice==3)
{
int low=0,high=0;
system("cls");
printf("\n Enter the price range from 21000 to 199999\n");
printf(" Enter lower range\n ");
scanf("%d",&low);
printf(" Enter higher range\n ");
scanf("%d",&high);
COMPUTER* temp;
temp=start;
int i=1,flag=0;
system("cls");
while(temp!=NULL)
{
if(temp->price>=low&&temp->price<=high)
{
printf("\n Option :%d\n\n NAME\t\t : %s \n Processor_name\t : %s CORE %s %s\n HDD_capacity\t : %s",i,temp->name,temp->brand,temp->processor_name,temp->processor_generation,temp-> HDD_capacity);
printf("\n Ram\t\t : %s \n Graphics\t : %s\n Operating System :%s\n PRICE\t\t : %fRs\n\n",temp->ram,temp->Graphics,temp->Operating_System,temp->price);
flag=1;
}
temp=temp->next;
i++;
}
if (flag==0)
{
MessageBox(0, "Item not found for the range you entered", "TECH CLOUD", MB_OK);
hardware_sec(start,order,soft,wake);
}
}
else if(choice==4)
spot(start,order,soft,wake);
else
{
MessageBox(0,"Invalid choice","TECH CLOUD",MB_OK);
hardware_sec(start,order,soft,wake);
}
printf("\n Your Choice? \n ");
scanf("%d",&op);
if(op<=0||op>30)
{
MessageBox(0, "Invalid choice", "TECH CLOUD", MB_OK);
printf("\n Enter any key to continue\n ");
getch();
spot(start,order,soft,wake);
}
system("cls");
printf("\n Add to Cart?\n\n");
COMPUTER* temp;
temp=start;
int i=1;
while(temp!=NULL)
{
if(i==op)
{
printf(" %s %s\n %f\n",temp->name,temp->model,temp->price);
if(temp->item==0)
{
printf("\n-----This ITEM IS OUT OF STOCK----\n");
MessageBox(0, " It is Notified to the Owner\n to Import this Item ", "TECH CLOUD", MB_OK);
FILE *fp;
fp=fopen("notification.txt","a");
fwrite(&temp->name,70,1,fp);
fclose(fp);
selec(start,order,soft,wake);
}
}
temp=temp->next;
i++;
}
printf("\n 1->YES\n 2->NO\n ");
scanf("%d",&ch2);
if(ch2==1)
{
COMPUTER* temp;
ORDER* now;
int i;
temp=start;
i=1;
while(temp!=NULL)
{
if(i==op)
{
now=order;
if(now==NULL)
{
now=(ORDER*)malloc(sizeof(ORDER));
strcpy(now->name,temp->name);
now->price=temp->price;
now->next=NULL;
order=now;
}
else
{
while(now->next!=NULL)
now=now->next;
now->next=(ORDER*)malloc(sizeof(ORDER));
strcpy(now->next->name,temp->name);
now->next->price=temp->price;
now->next->next=NULL;
}
temp->item--;
}
temp=temp->next;
i++;
}
}
else
{
spot(start,order,soft,wake);
}
int other=0;
system("cls");
printf("\n Continue Shopping?\n");
printf(" 1->YES\n 2->NO\n ");
scanf("%d",&other);
if(other==1)
spot(start,order,soft,wake);
else
{
buy(order,start,soft,wake);
}
}
else if(ch1==2)
{
STORAGE* pend=NULL;
pend=get_pend();
STORAGE* temp=NULL;
temp=pend;
system("cls");
printf(" -------------------------------------------------------------------\n");
printf(" PENDRIVES SECTION \n");
printf(" -------------------------------------------------------------------\n\n");
while(temp!=NULL)
{
printf(" Option :%d\n Name : %s\n Price : %f\n\n",i,temp->name,temp->price);
temp=temp->next;
i++;
}
printf(" To continue, enter any key...\n ");
getch();
int cho=0,op=0;
printf("\n Your Choice?\n ");
scanf("%d",&op);
if(op<=0||op>5)
{
MessageBox(0, "Invalid choice", "TECH CLOUD", MB_OK);
spot(start,order,soft,wake);
}
system("cls");
printf("\n Add to Cart?\n");
i=1;
STORAGE* cur;
cur=pend;
while(cur!=NULL)
{
if(i==op)
{
printf(" %s \n %f\n\n",cur->name,cur->price);
if(cur->item==0)
{
printf("\n-----This ITEM IS OUT OF STOCK----\n");
MessageBox(0, " It is Notified to the Owner\n to Import this Item ", "TECH CLOUD", MB_OK);
FILE *fp;
fp=fopen("notification.txt","a");
fwrite(&cur->name,70,1,fp);
fclose(fp);
selec(start,order,soft,wake);
}
}
i++;
cur=cur->next;
}
printf(" 1->YES\n 2->NO\n ");
scanf("%d",&cho);
if(cho==1)
{
STORAGE* temp;
ORDER* now;
int i;
temp=pend;
i=1;
while(temp!=NULL)
{
if(i==op)
{
now=order;
if(now==NULL)
{
now=(ORDER*)malloc(sizeof(ORDER));
strcpy(now->name,temp->name);
now->price=temp->price;
now->next=NULL;
order=now;
}
else
{
while(now->next!=NULL)
now=now->next;
now->next=(ORDER*)malloc(sizeof(ORDER));
strcpy(now->next->name,temp->name);
now->next->price=temp->price;
now->next->next=NULL;
}
temp->item--;
}
temp=temp->next;
i++;
}
}
int other=0;
system("cls");
printf("\n Do tou want to Continue Shopping?\n");
printf(" 1->YES\n 2->NO\n ");
scanf("%d",&other);
if(other==1)
spot(start,order,soft,wake);
else
{
buy(order,start,soft,wake);
order=NULL;
}
}
else if(ch1==3)
{
STORAGE* hd=NULL;
hd=get_hd();
STORAGE* temp=NULL;
temp=hd;
system("cls");
printf(" -------------------------------------------------------------------\n");
printf(" HARDDISK SECTION \n");
printf(" -------------------------------------------------------------------\n\n");
while(temp!=NULL)
{
printf(" Option :%d\n Name : %s\n Price : %f\n\n",i,temp->name,temp->price);
temp=temp->next;
i++;
}
printf(" To continue, enter any key...\n ");
getch();
int cho=0,op=0;
printf("\n Your Choice?\n ");
scanf("%d",&op);
if(op<=0||op>5)
{
MessageBox(0, "Invalid choice", "TECH CLOUD", MB_OK);
getch();
spot(start,order,soft,wake);
}
system("cls");
printf("\n Add to Cart?\n");
i=1;
STORAGE* cur;
cur=hd;
while(cur!=NULL)
{
if(i==op)
{
printf(" %s\n\n",cur->name);
if(cur->item==0)
{
printf("\n-----This ITEM IS OUT OF STOCK----\n");
MessageBox(0, " It is Notified to the Owner\n to Import this Item ", "TECH CLOUD", MB_OK);
FILE *fp;
fp=fopen("notification.txt","a");
fwrite(&cur->name,70,1,fp);
fclose(fp);
selec(start,order,soft,wake);
}
}
i++;
cur=cur->next;
}
printf(" 1->YES\n 2->NO\n ");
scanf("%d",&cho);
if(cho==1)
{
STORAGE* temp;
ORDER* now;
int i;
temp=hd;
i=1;
while(temp!=NULL)
{
if(i==op)
{
now=order;
if(now==NULL)
{
now=(ORDER*)malloc(sizeof(ORDER));
strcpy(now->name,temp->name);
now->price=temp->price;
now->next=NULL;
order=now;
}
else
{
while(now->next!=NULL)
now=now->next;
now->next=(ORDER*)malloc(sizeof(ORDER));
strcpy(now->next->name,temp->name);
now->next->price=temp->price;
now->next->next=NULL;
}
temp->item--;
}
temp=temp->next;
i++;
}
}
int other=0;
system("cls");
printf("\n Continue Shopping?\n");
printf(" 1->YES\n 2->NO\n ");
scanf("%d",&other);
if(other==1)
spot(start,order,soft,wake);
else
{
buy(order,start,soft,wake);
order=NULL;
}
}
else if (ch1==4)
{
spot(start,order,soft,wake);
}
else
{
MessageBox(0,"Invalid choice","TECH CLOUD",MB_OK);
hardware_sec(start,order,soft,wake);
}
}
///Function Name : software_sec
///Description : Function Provides software products and can be ordered it in 'spot shopping'
///Input Params : soft,order,start,wake
///Return : void
void software_sec(SOFTWARE* soft,ORDER* order,COMPUTER* start,QUEUE* wake)
{
system("cls");
printf(" -------------------------------------------------------------------------\n");
printf(" 'SOFTWARE COMPUTER SERVICES' SECTION \n");
printf(" -------------------------------------------------------------------------\n");
SOFTWARE* temp=NULL;
temp=soft;
int i=1;
while(temp!=NULL)
{
printf(" Option : %d\n Name : %s\n Price : %f\n\n",i,temp->name,temp->price);
temp=temp->next;
i++;
}
int cho=0,op=0;
printf(" Your Choice?\n ");
scanf("%d",&op);
if(op<=0||op>5)
{
printf(" Invalid Option\n ");
getch();
spot(start,order,soft,wake);
}
system("cls");
printf("\n Add to Cart?\n\n");
i=1;
SOFTWARE* cur;
cur=soft;
while(cur!=NULL)
{
if(i==op)
{
printf(" %s\n Price:%f \n\n",cur->name,cur->price);
if(cur->item==0)
{
printf("\n-----This ITEM IS OUT OF STOCK----\n");
MessageBox(0, " It is Notified to the Owner\n to Import this Item ", "TECH CLOUD", MB_OK);
FILE *fp;
fp=fopen("notification.txt","a");
fwrite(&cur->name,70,1,fp);
fclose(fp);
selec(start,order,soft,wake);
}
}
i++;
cur=cur->next;
}
printf("\n 1->YES\n 2->NO\n ");
scanf("%d",&cho);
if(cho==1)
{
SOFTWARE* temp;
QUEUE* now;
int i;
temp=soft;
now=wake;
i=1;
while(temp!=NULL)
{
if(i==op)
{
now=order;
if(now==NULL)
{
now=(ORDER*)malloc(sizeof(ORDER));
strcpy(now->name,temp->name);
now->price=temp->price;
now->next=NULL;
order=now;
}
else
{
while(now->next!=NULL)
now=now->next;
now->next=(ORDER*)malloc(sizeof(ORDER));
strcpy(now->next->name,temp->name);
now->next->price=temp->price;
now->next->next=NULL;
}
temp->item--;
}
temp=temp->next;
i++;
}
system("cls");
printf("\n Item Added to Cart\n\n");
printf(" To continue, enter any key...\n ");
getch();
}
else
{
spot(start,order,soft,wake);
}
int other=0;
system("cls");
printf("\n DO u want to Continue Shopping? \n");
printf(" 1->YES\n 2->NO\n ");
scanf("%d",&other);
if(other==1)
spot(start,order,soft,wake);
else
{
buy(order,start,soft,wake);
order=NULL;
}
}
///Function Name : buy
///Description : Function provides you the options for further orders or discarding the previous orders or completion of order
///Input Params : order,start,soft,wake
///Return : void
void buy(ORDER* order,COMPUTER* start,SOFTWARE* soft,QUEUE* wake)
{
int pq=0;
system("cls");
///if t=0 "Complete the Order" otherwise "Display Cart"
if(t==0)
{
printf("\n Your Orders Are....\n\n");
}
else
{
printf("\n----------------------------------------------------------------------------- ");
printf("\n YOUR CART ");
printf("\n-----------------------------------------------------------------------------\n\n");
}
ORDER* ord;
ord=order;
int o=1;
if(ord==NULL)
{
MessageBox(0, "Your cart is empty", "TECH CLOUD", MB_OK);
t=0;
return;
}
else
{
while(ord!=NULL)
{
printf(" %d\n Name : %s\n Price: %f\n\n",o,ord->name,ord->price);
ord=ord->next;
o++;
}
}
if(t==0)
{
printf(" 1->Add More items to the Order\n");
printf(" 2->Discard Any of Items in Order\n");
printf(" 3->Check Out\n ");
}
else
{
printf(" 1->Add More items to the Cart\n");
printf(" 2->Discard Any of Items in Cart\n");
printf(" 3->Buy now\n ");
}
t=0;
int choo=0,opn=0;
scanf("%d",&choo);
switch(choo)
{
case 1:
spot(start,order,soft,wake);
break;
case 2:
printf("\n Enter the Option of item to be Discarded\n ");
scanf("%d",&opn);
if(opn<1 || opn>=o)
MessageBox(0, "Invalid choice", "TECH CLOUD", MB_OK);
else
{
order=discard(order,opn);
}
buy(order,start,soft,wake);
break;
case 3: pq=cont(order);
if(pq==1)
{
spot(start,order,soft,wake);
}
break;
default : MessageBox(0, "Invalid choice", "TECH CLOUD", MB_OK);
break;
}
}
///Function Name : cont
///Description : Function provides you Completion of Orders and Generation of bill
///Input Params : order
///Return : void
int cont(ORDER* order)
{
float total_bill[30],tot_bill=0;
int discount[30],i=0,flag=0;
char name[20],number[11];
system("cls");
ORDER* pur;
pur=order;
if(pur==NULL)
{
MessageBox(0, "Your cart is empty", "TECH CLOUD", MB_OK);
MessageBox(0, " Please Buy Anything..!!!\nDon't Miss the Offers...!!!", "TECH CLOUD", MB_OK);
return 1;
}
else
{
system("cls");
printf("\n Enter the following details\n\n");
printf(" Name: ");
scanf("%s",name);
printf("\n Contact Number: ");
scanf("%s",number);
system("cls");
get_payment_method(&flag);
system("cls");
printf("\n Order is placed Successful\n");
printf("\n Enter any key to generate the bill....\n");
getch();
system("cls");
ORDER* curr;
curr=order;
while(curr!=NULL)
{
discount[i]=discnt();
total_bill[i]=curr->price-(discount[i]*curr->price/100);
curr=curr->next;
i++;
}
ORDER* cur;
cur=order;
int k=0;
while(cur!=NULL)
{
k++;
cur=cur->next;
}
rtrn();
printf(" ------------------------------------------------------------------------------\n");
printf(" TECH CLOUD \n");
printf(" ------------------------------------------------------------------------------\n");
printf(" BILL NO : %d \n\n",bill);
printf(" NAME : %s \n\n",name);
printf(" Contact Number : %s \n\n",number);
printf(" Total Items Purchased: %d \n\n",k);
curr=order;
i=0;
printf(" ------------------------------Order Summary------------------------------------\n\n");
while(curr!=NULL)
{
printf(" NAME : %s \n\n",curr->name);
printf(" Price : %f \n\n",curr->price);
printf(" Discount : %d %% \n\n",discount[i]);
printf(" Bill : %f \n\n",total_bill[i]);
tot_bill=tot_bill+total_bill[i];
curr=curr->next;
i++;
}
printf(" ==============================================================================\n");
printf(" TOTAL BILL : %f \n\n",tot_bill);
printf(" ==============================================================================\n");
printf("\n Payment method : ");
if(flag==1)
printf(" Used CREDIT/DEBIT cards\n");
else
printf(" Pay by cash");
bill++;
order=NULL;
printf("\n\n To continue, enter any key...\n ");
getch();
printf("\a\a");
MessageBox(0, "Thank You!! VISIT AGAIN! :)", "TECH CLOUD", MB_OK);
return 0;
}
}
void get_payment_method(int *flag)
{
int ch;ATM C;
printf("\n Select the payment method\n");
printf("\n 1->Credit card / Debit card /ATM Card \n");
printf(" 2->Cash on delivery\n ");
printf("\n Enter your choice \n ");
scanf("%d",&ch);
switch(ch)
{
case 1 : *flag=1;
printf("\n\n Enter the following Details\n\n");
printf("\n Card number: ");
scanf("%Lf",&C.card_number);
printf(" Expiry date: ");
scanf("%d",&C.mm);
printf(" Expiry year: ");
scanf("%d",&C.yyyy);
printf(" CVV: ");
scanf("%d",&C.CVV);
system("cls");
printf("\n Your card details \n");
printf("\n Card number : %Lf \n Expiry mm : %d \n YYYY : %d \n CVV : %d",C.card_number,C.mm,C.yyyy,C.CVV);
MessageBox(0, "Your payment is succesfully completed", "TECH CLOUD", MB_OK);
break;
case 2 : *flag=2;
break;
default : MessageBox(0, "Invalid choice", "TECH CLOUD", MB_OK);
system("cls");
get_payment_method(flag);
break;
}
}
///Function Name : discnt
///Description : function to compute discount by finding the date and month
///Input Params : nill
///Return : discount percentage
int discnt()
{
char m[4];
int mm=0,discount=0;
timendate(m);
mm=find_m(m);
discount=dis(mm);
return discount;
}
///Function Name : rtrn
///Description : functiom to find month
///Input Params : nill
///Return : void
void rtrn()
{
char m[4];
int mm=0;
timendate(m);
mm=find_m(m);
prnt(mm);
}
///Function Name : discard
///Description : Function provides you to discard the previous orders
///Input Params : order,opn
///return : updated order
ORDER* discard(ORDER* order,int opn)
{
int i=1;
ORDER* temp=NULL;
ORDER* pre=NULL;
temp=order;
pre=NULL;
if(opn==1)
{
order=temp->next;
}
else
{
while(i!=opn)
{
pre=temp;
temp=temp->next;
i++;
}
pre->next=temp->next;
}
free(temp);
return order;
}
///Function Name : search
///Input : key or pattern, list of hardware and software products
///Output : Found Items for given key in Sorted order and display in increasing order of price
///Description : Provides functionalities for searching based on key and sorts the found items based on price
void search(char* key,COMPUTER* start,SOFTWARE* soft)
{
int n,m,x=0,p;
SEARCH S[50];
COMPUTER* temp;
temp=start;
int i=0,j=0;
int s_l=0,s_h=0,s_s=0,s_p=0;
char *p1,*p2,*p3;
while(temp!=NULL)
{
p1=temp->name;
p2=key;
for(i=0;i< strlen(temp->name);i++)
{
if(*p1==*p2)
{
p3=p1;
for(j=0;j<strlen(key);j++)
{
if(*p3==*p2)
{
p3++;p2++;
}
else
break;
}
p2=key;
if(j==strlen(key))
{
strcpy(S[x].name,temp->name);
S[x].price=temp->price;
s_l++;
x++;
break;
}
}
p1++;
}
temp=temp->next;
}
SOFTWARE* t2=NULL;
t2=soft;
i=0,j=0;
while(t2!=NULL)
{
p1=t2->name;
p2=key;
for(i=0;i<strlen(t2->name);i++)
{
if(*p1==*p2)
{
p3=p1;
for(j=0;j<strlen(key);j++)
{
if(*p3==*p2)
{
p3++;p2++;
}
else
break;
}
p2=key;
if(j==strlen(key))
{
strcpy(S[x].name,t2->name);
S[x].price=t2->price;
s_s++;
x++;
break;
}
}
p1++;
}
t2=t2->next;
}
STORAGE* pend=NULL;
pend=get_pend();
STORAGE* t3=NULL;
t3=pend;
i=0,j=0;
while(t3!=NULL)
{
p1=t3->name;
p2=key;
for(i=0;i<strlen(t3->name);i++)
{
if(*p1==*p2)
{
p3=p1;
for(j=0;j<strlen(key);j++)
{
if(*p3==*p2)
{
p3++;p2++;
}
else
break;
}
p2=key;
if(j==strlen(key))
{
strcpy(S[x].name,t3->name);
S[x].price=t3->price;
s_p++;
x++;
break;
}
}
p1++;
}
t3=t3->next;
}
STORAGE* hd=NULL;
hd=get_hd();
STORAGE* t1=NULL;
t1=hd;
i=0,j=0;
while(t1!=NULL)
{
p1=t1->name;
p2=key;
for(i=0;i<strlen(t1->name);i++)
{
if(*p1==*p2)
{
p3=p1;
for(j=0;j<strlen(key);j++)
{
if(*p3==*p2)
{
p3++;p2++;
}
else
break;
}
p2=key;
if(j==strlen(key))
{
strcpy(S[x].name,t1->name);
S[x].price=t1->price;
s_h++;
x++;
break;
}
}
p1++;
}
t1=t1->next;
}
float tempr;
char tempry[20];
for(i=0;i<=(s_l + s_s+ s_h+ s_p)-2;i++)
{
for(j=0;j<=(s_l + s_s+ s_h+ s_p)-2-i;j++)
{
if(S[j+1].price<S[j].price)
{
strcpy(tempry,S[j].name);
tempr=S[j].price;
strcpy(S[j].name,S[j+1].name);
S[j].price=S[j+1].price;
strcpy(S[j+1].name,tempry);
S[j+1].price=tempr;
}
}
}
if(s_l==0 && s_h==0 && s_s==0 && s_p==0)
{
printf("\n Search not found\n");
}
else
{
printf("\n Search found........\n\n");
for(p=0;p<(s_l + s_s+ s_h+ s_p);p++)
{
printf(" %s \n",S[p].name);
printf(" %f\n",S[p].price);
printf(" \n");
}
}
printf("\n Enter any key to continue\n");
getch();
}
///Function Name : export
///Input : starting address of hardware and software items list
///return type : void
///Description :Provides options for Exporting the Items to different branches based on Dijkstras Minimum path algorithm
void export(COMPUTER* start,SOFTWARE* soft)
{
int op,destn;
i=1;
COMPUTER* temp;
temp=start;
system("cls");
printf("\n ---------------------------LAPTOPS---------------------- ITEMS REMAINING\n\n");
while(temp!=NULL)
{
printf(" Option:%d %s%s\n",i,temp->brand,temp->name);
printf("\n\t\t\t\t\t\t\t\t%d\n\n",temp->item);
temp=temp->next;
i++;
}
STORAGE* t2=NULL;
t2=get_pend();
printf("\n -------------------------PENDRIVESe---------------------- ITEMS REMAINING\n\n");
while(t2!=NULL)
{
printf(" Option:%d %s\n",i,t2->name);
printf("\n\t\t\t\t\t\t\t\t%d\n\n",t2->item);
t2=t2->next;
i++;
}
STORAGE* t3=NULL;
t3=get_hd();
printf("\n -------------------------HARDDISKS----------------------- ITEMS REMAINING\n\n");
while(t3!=NULL)
{
printf(" Option:%d %s\n",i,t3->name);
printf("\n\t\t\t\t\t\t\t\t%d\n\n",t3->item);
t3=t3->next;
i++;
}
SOFTWARE* t;
t=soft;
printf("\n -----------------------SOFTWARE PRODUCTS------------------ ITEMS REMAINING\n\n");
while(t!=NULL)
{
printf(" Option:%d %s",i,t->name);
printf("\n\t\t\t\t\t\t\t\t%d\n\n",t->item);
t=t->next;
i++;
}
printf("\n ---------------------------------------------------------------------------\n");
printf("\n\n Enter the option of item ..to export\n ");
scanf("%d",&op);
while(op>45 || op<0)
{
printf("\n\n Invalid choice\n");
printf("\n Enter your choice again\n ");
scanf("%d",&op);
}
printf("\n Select the place 'from where' you want to export\n");
printf(" 1->Hubli\n 2->Bengaluru\n 3->Mumbai\n 4->Chennai\n 5->Hyderabad\n ");
/*DIJKTRAS shortest path algorithm*/
int n,cost[10][10],i,j,d[10],p[10],source;
n=5;
FILE* fp;
fp=fopen("Distance.txt","r");
if(fp==NULL)
{
printf(" Distance file not found \n");
exit(0);
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
fscanf(fp,"%d",&cost[i][j]);
}
}
fclose(fp);
scanf("%d",&source);
while(source>5 || source<0)
{
printf("\n Invalid choice\n");
printf("\n Enter your choice again\n");
scanf("%d",&source);
}
dijkstras(n,cost,source,j,d,p);
printf("\n\n Select the place 'where' you want to Export the Item\n");
printf(" 1->Hubli\n 2->Bengaluru\n 3->Mumbai\n 4->Chennai\n 5->Hyderabad\n ");
scanf("%d",&destn);
while(destn>5 || destn<0)
{
printf("\n Invalid choice\n");
printf("\n Enter your choice again\n ");
scanf("%d",&destn);
}
int item;
char name[60];
temp=start;
system("cls");
i=1;
while(temp!=NULL)
{
if(op==i)
{
temp->item--;
strcpy(name,temp->name);
item=temp->item;
}
temp=temp->next;
i++;
}
STORAGE* t6=NULL;
t6=get_pend();
while(t6!=NULL)
{
printf(" Option:%d %s\n",i,t6->name);
if(op==i)
{
t6->item--;
strcpy(name,t6->name);
item=t6->item;
}
t6=t6->next;
i++;
}
STORAGE* t7=NULL;
t7=get_hd();
while(t7!=NULL)
{
printf(" Option:%d %s\n",i,t7->name);
if(op==i)
{
t7->item--;
strcpy(name,t7->name);
item=t7->item;
}
t7=t7->next;
i++;
}
t=soft;
while(t!=NULL)
{
printf(" Option:%d %s\n",i,t->name);
if(op==i)
{
t->item--;
strcpy(name,t->name);
item=t->item;
}
t=t->next;
i++;
}
system("cls");
printf("\n -----------------------------------------------------------------------\n");
printf(" \t\t\t\tExport\t\t\t\n");
printf(" -----------------------------------------------------------------------\n");
MessageBox(0,"Item Exported to Required Destination","TECH CLOUD",MB_OK);
printpath(d,p,n,source,destn);
printf("\n ITEM DETAILS : ");
printf("\n Item : %s",name);
printf("\n The items after export : %d\n",item);
printf("\n\n Enter any key to go back\n ");
getch();
}
void printpath(int d[],int p[],int n,int source,int destn)
{
int dest,i;
char place[20];
for(dest=1;dest<=n;dest++)
{
if(dest==destn)
{
i=dest;
if(d[i]==999)
printf(" %d is not reachable\n",i);
else
{
printf("\n The shipping details :");
while(i!=source)
{
strcpy( place,getplace(i));
printf(" %s<---",place);
i=p[i];
}
printf(" %s \n Transportation charges : Rs %d\n",getplace(i),d[dest]);
}
}
}
}
char* getplace(int n)
{
if(n==1) return ("HUBLI");
if(n==2) return("BENGALORE");
if(n==3) return("MUMBAI");
if(n==4) return("CHENNAI");
if(n==5) return("HYDERABAD");
}
void dijkstras(int n,int cost[10][10],int source,int dest,int d[],int p[])
{
int i,j,u,v;
int min;
int s[10];
for(i=1;i<=n;i++)
{
d[i]=cost[source][i];
s[i]=0;
p[i]=source;
}
s[source]=1;
for(i=1;i<n;i++)
{
min=999;
u=-1;
for(j=1;j<=n;j++)
{
if(s[j]==0)
{
if(d[j]<=min)
{
min=d[j];
u=j;
}
}
}
if(u==-1)
return;
s[u]=1;
if(u==dest)
return;
for(v=1;v<=n;v++)
{
if(s[v]==0)
{
if(d[u]+cost[u][v]<d[v])
{
d[v]=d[u]+cost[u][v];
p[v]=u;
}
}
}
}
}
///Function Name : import
///Input : starting address of Hardware and Software items list
///return type : void
///Description : Provides options for Importing the Items from differnt branches based on Dijkstras Minimum path algorithm
void import(COMPUTER* start,SOFTWARE* soft)
{
int op,destn;
i=1;
COMPUTER* temp=NULL;
temp=start;
system("cls");
printf("\n ---------------------------LAPTOPS---------------------- ITEMS REMAINING\n\n");
while(temp!=NULL)
{
printf(" Option:%d %s%s\n",i,temp->brand,temp->name);
printf("\n\t\t\t\t\t\t\t\t%d\n\n",temp->item);
temp=temp->next;
i++;
}
STORAGE* t2=NULL;
t2=get_pend();
printf("\n -------------------------PENDRIVES---------------------- ITEMS REMAINING\n\n");
while(t2!=NULL)
{
printf(" Option:%d %s\n",i,t2->name);
printf("\n\t\t\t\t\t\t\t\t%d\n\n",t2->item);
t2=t2->next;
i++;
}
STORAGE* t3=NULL;
t3=get_hd();
printf("\n -------------------------HARDDISKS----------------------- ITEMS REMAINING\n\n");
while(t3!=NULL)
{
printf(" Option:%d %s\n",i,t3->name);
printf("\n\t\t\t\t\t\t\t\t%d\n\n",t3->item);
t3=t3->next;
i++;
}
SOFTWARE* t;
t=soft;
printf("\n -----------------------SOFTWARE PRODUCTS------------------ ITEMS REMAINING\n\n");
while(t!=NULL)
{
printf(" Option:%d %s\n",i,t->name);
printf("\n\t\t\t\t\t\t\t\t%d\n\n",t->item);
t=t->next;
i++;
}
printf("\n ---------------------------------------------------------------------------\n");
printf("\n\n Enter the option of item ..to import\n ");
scanf("%d",&op);
while(op>45 || op<0)
{
MessageBox(0,"Invalid choice","TECH CLOUD",MB_OK);
printf("\n Enter your choice again\n ");
scanf("%d",&op);
}
printf("\n\n Select the place 'from where' you want to import the item \n ");
printf("\n 1->Hubli\n 2->Bengaluru\n 3->Mumbai\n 4->Chennai\n 5->Hyderabad\n ");
/*DIJKTRAS shortest path algorithm*/
int n,cost[10][10],i,j,d[10],p[10],source;
n=5;
FILE* fp;
fp=fopen("Distance.txt","r");
if(fp==NULL)
{
MessageBox(0,"Distance file not found ","TECH CLOUD",MB_OK);
exit(0);
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
fscanf(fp,"%d",&cost[i][j]);
}
}
fclose(fp);
scanf("%d",&source);
while(source>5 || source<0)
{
MessageBox(0,"Invalid choice","TECH CLOUD",MB_OK);
printf("\n Enter your choice again\n ");
scanf("%d",&source);
}
dijkstras(n,cost,source,j,d,p);
printf("\n\n Select the place 'where' you want to import the item \n");
printf("\n 1->Hubli\n 2->Bengaluru\n 3->Mumbai\n 4->Chennai\n 5->Hyderabad\n ");
scanf("%d",&destn);
while(destn>5 || destn<0)
{
MessageBox(0,"Invalid choice","TECH CLOUD",MB_OK);
printf(" Enter your choice again\n ");
scanf("%d",&destn);
}
int item;
char name[60];
temp=start;
system("cls");
i=1;
while(temp!=NULL)
{
if(op==i)
{
temp->item++;
strcpy(name,temp->name);
item=temp->item;
}
temp=temp->next;
i++;
}
STORAGE* t6=NULL;
t6=get_pend();
while(t6!=NULL)
{
printf(" Option:%d %s\n",i,t6->name);
if(op==i)
{
t6->item--;
strcpy(name,t6->name);
item=t6->item;
}
t6=t6->next;
i++;
}
STORAGE* t7=NULL;
t7=get_hd();
while(t7!=NULL)
{
printf(" Option:%d %s\n",i,t7->name);
if(op==i)
{
t7->item--;
strcpy(name,t7->name);
item=t7->item;
}
t7=t7->next;
i++;
}
t=soft;
while(t!=NULL)
{
printf(" Option:%d %s\n",i,t->name);
if(op==i)
{
t->item++;
strcpy(name,t->name);
item=t->item;
}
t=t->next;
i++;
}
system("cls");
printf("\n -----------------------------------------------------------------------\n");
printf(" \t\t\t\tImport\t\t\t\n");
printf("-----------------------------------------------------------------------\n");
MessageBox(0," Item Imported from Required Destination ","TECH CLOUD",MB_OK);
printpath(d,p,n,source,destn);
printf("\n Item Details : \n");
printf("\n Item : %s",name);
printf("\n The items after import : %d\n",item);
printf("\n\n Enter any key to go back\n ");
getch();
}
|
C | #include "uart.h"
// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
// flag register bits
#define TXFE (1 << 7)
#define RXFF (1 << 6)
#define TXFF (1 << 5)
#define RXFE (1 << 4)
#define BUSY (1 << 3)
#define CTS (1 << 0)
// dr register bits
#define OE (1 << 11)
#define BE (1 << 10)
#define PE (1 << 9)
#define FE (1 << 8)
// cr register bits
#define UARTEN (1 << 0)
// lcrh register bits
#define FEN (1 << 4)
// imsc register bits
#define RXIM (1 << 4)
// irc register bits
#define RXIC (1 << 4)
// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
// fifo
#define QUEUE_ELEMENTS 1024
#define QUEUE_SIZE (QUEUE_ELEMENTS + 1)
static unsigned char Queue[QUEUE_SIZE];
static unsigned char QueueIn;
static unsigned char QueueOut;
// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
// uart register access
#define UART_BASE (0X7E201000 - 0X3F000000)
struct uart_t {
unsigned int dr;
unsigned int rsrecr;
unsigned int unused0[4];
unsigned int fr;
unsigned int unused1;
unsigned int ilpr;
unsigned int ibrd;
unsigned int fbrd;
unsigned int lcrh;
unsigned int cr;
unsigned int ifls;
unsigned int imsc;
unsigned int ris;
unsigned int mis;
unsigned int icr;
};
static volatile struct uart_t *const uart = (struct uart_t *)UART_BASE;
void init_uart()
{
wait(8388608/10);
uart->cr &= ~UARTEN; // disable uart
wait(8388608/10);
// configure UART
uart->lcrh &= ~FEN; // disable hardware FIFOs
uart->imsc |= RXIM; // enable RXIM (recieve interrupt mask)
uart->cr |= UARTEN; // enable uart
wait(8388608/10);
// fifo init
QueueIn = 0;
QueueOut = 0;
}
/*
* write argument char c into data reg if TXFF flag is 0
*/
void uart_putc(unsigned char c)
{
while (uart->fr & TXFF)
continue;
uart->dr = c;
}
/*
* read a character from data register
* returns 0 on success - -1 if queue is empty
*/
int uart_getc(unsigned char *c)
{
// fifo get(c)
if(QueueIn == QueueOut)
return -1; // queue empty - nothing to get
*c = Queue[QueueOut];
QueueOut = (QueueOut + 1) % QUEUE_SIZE;
return 0;
}
void uart_rx_irq_handler()
{
unsigned int dr = uart->dr;
// error checking
if (dr & (OE | BE | PE | FE))
return;
// fifo put(dr)
if (QueueIn == ((QueueOut - 1 + QUEUE_SIZE) % QUEUE_SIZE))
return; // queue full
Queue[QueueIn] = (unsigned char)dr;
QueueIn = (QueueIn + 1) % QUEUE_SIZE;
return;
}
void uart_rx_irq_ack()
{
uart->icr |= RXIC; // clears the interrupt (UARTRXINTR)
}
|
C | // Sequência espelho
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main()
{
int num1, num2, testes, i, j = 0;
char numChar[5];
scanf(" %d", &testes);
for(testes; testes > 0; testes--)
{
scanf(" %d%d", &num1, &num2);
for(i = num1; i <= num2; i++)
{
sprintf(numChar, "%d", i);
printf("%s", numChar);
}
for(i = num2; i >= num1; i--)
{
sprintf(numChar, "%d", i);
j = strlen(numChar);
for(j -= 1; j >= 0; j--)
{
printf("%c", numChar[j]);
}
}
printf("\n");
}
} |
C | //
// main.c
// DS_HW2_Dijkstra
//
// Created by GONG, YI-JHONG on 2015/11/20.
// Copyright © 2015年 GONG, YI-JHONG. All rights reserved.
// NOTE: There is a known issue for reading large input.
#include <stdio.h>
#define MAX_GRAPH 2048
#define INF MAX_GRAPH * MAX_GRAPH
#define TRUE 1
#define FALSE 0
int cost[MAX_GRAPH][MAX_GRAPH];
//this table is recorded for node-to-node cost.
int distance[MAX_GRAPH][2] = {0};
//the first row records the accumulate distance; the second row records the next node
short int found[MAX_GRAPH] = {0};
//table for marking which point is visited before.
int route[MAX_GRAPH];
int top = MAX_GRAPH;
void dijkstra(int start, int end, int maxVertex){
int nextNode = start, tmpNextNode = start, i;
int minCost;
int allVisited = FALSE;
distance[start][0] = 0;
found[start] = TRUE;
while (!allVisited) {
minCost = INF;
allVisited = TRUE;
for (i = 0; i <= maxVertex; i++) {
if (cost[nextNode][i] != INF && !found[i] && distance[i][0] > distance[nextNode][0] + cost[nextNode][i]) {
distance[i][0] = distance[nextNode][0] + cost[nextNode][i];
distance[i][1] = nextNode;
}
if (cost[nextNode][i] != INF && !found[i]) {
if (minCost > distance[i][0]) {
minCost = distance[i][0];
tmpNextNode = i;
}
allVisited = FALSE;
}
}
found[tmpNextNode] = TRUE;
nextNode = tmpNextNode;
}
return;
}
void traceRoute(int start, int end){
int nextNode = end, i;
route[--top] = end;
while (nextNode != start) {
route[--top] = distance[nextNode][1];
nextNode = distance[nextNode][1];
}
for (i = 0; i < MAX_GRAPH - 1; i++) {
if (route[i] != -1) {
printf("%d ", route[i]);
}
}
printf("%d", route[MAX_GRAPH - 1]);
printf("\n%d\n", distance[end][0]);
}
void initialize(){
int i, j;
for (i = 0; i < MAX_GRAPH; i++) {
distance[i][0] = INF;
distance[i][1] = FALSE;
found[i] = FALSE;
route[i] = -1;
for (j = 0; j < MAX_GRAPH; j++) {
cost[i][j] = INF;
}
}
return;
}
int main(int argc, char *argv[]) {
FILE *inputFile;
int count, i;
int beginNode, endNode, start, end, costValue, maxVertex = 0;
inputFile = fopen("map.txt", "r");
initialize();
fscanf(inputFile,"%d", &count);
fflush(stdin);
for (i = 0; i < count; i++){
fscanf(inputFile,"%d%d%d", &beginNode, &endNode, &costValue);
if (maxVertex < beginNode) {
maxVertex = beginNode;
}
cost[beginNode][endNode] = costValue;
}
fscanf(inputFile,"%d%d", &start, &end);
dijkstra(start, end, maxVertex);
traceRoute(start, end);
return 0;
} |
C | #include <stdio.h>
int main(int argc, char *argv[]){
FILE * myarquivo;
char texto;
if(argc < 2){
printf("Por favor, informe o nome de arquivo que deseja ler como parametro do programa.");
exit(1);
}
myarquivo = fopen(argv[1], "r");
if(myarquivo == NULL){
printf("Erro ao abrir o arquivo");
exit(1);
}
else{
while(!feof(myarquivo)){
fscanf(myarquivo, "%c", &texto);
printf("%c", texto);
}
}
fclose(myarquivo);
return 0;
}
|
C | /***
*time.c - get current system time
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
*Purpose:
* defines _time32() - gets the current system time and converts it to
* internal (__time32_t) format time.
*
*******************************************************************************/
#include <cruntime.h>
#include <time.h>
#include <ctime.h>
#include <internal.h>
#include <windows.h>
/*
* Number of 100 nanosecond units from 1/1/1601 to 1/1/1970
*/
#define EPOCH_BIAS 116444736000000000i64
/*
* Union to facilitate converting from FILETIME to unsigned __int64
*/
typedef union {
unsigned __int64 ft_scalar;
FILETIME ft_struct;
} FT;
/***
*__time32_t _time32(timeptr) - Get current system time and convert to a
* __time32_t value.
*
*Purpose:
* Gets the current date and time and stores it in internal (__time32_t)
* format. The time is returned and stored via the pointer passed in
* timeptr. If timeptr == NULL, the time is only returned, not stored in
* *timeptr. The internal (__time32_t) format is the number of seconds since
* 00:00:00, Jan 1 1970 (UTC).
*
* Note: We cannot use GetSystemTime since its return is ambiguous. In
* Windows NT, in return UTC. In Win32S, probably also Win32C, it
* returns local time.
*
*Entry:
* __time32_t *timeptr - pointer to long to store time in.
*
*Exit:
* returns the current time.
*
*Exceptions:
*
*******************************************************************************/
__time32_t __cdecl _time32 (
__time32_t *timeptr
)
{
__time64_t tim;
FT nt_time;
GetSystemTimeAsFileTime( &(nt_time.ft_struct) );
tim = (__time64_t)((nt_time.ft_scalar - EPOCH_BIAS) / 10000000i64);
if (tim > (__time64_t)(_MAX__TIME32_T))
tim = (__time64_t)(-1);
if (timeptr)
*timeptr = (__time32_t)(tim); /* store time if requested */
return (__time32_t)(tim);
}
|
C | #include <stdio.h>
#include <stdlib.h>
//A C example about or statements
int main() {
char answer;
printf("Do you like bagels? (Y/N)?: \n");
scanf(" %c", &answer);
if((answer == 'Y') || (answer == 'N')) {
printf("Great me too!");
} else{
printf("Aww you suck.");
}
return 0;
}
|
C | //
// Created by kenhuang on 19-10-20.
//
#ifndef type_H
#define type_H
typedef long (* Function)();
typedef unsigned char boolean; /* Boolean value type. */
typedef unsigned long int uint32; /* Unsigned 32 bit value */
typedef unsigned short uint16; /* Unsigned 16 bit value */
typedef unsigned char uint8; /* Unsigned 8 bit value */
typedef signed long int int32; /* Signed 32 bit value */
typedef signed short int16; /* Signed 16 bit value */
typedef signed char int8; /* Signed 8 bit value */
typedef unsigned char byte;
typedef unsigned short word;
#define bool short
#define true 1
#define false 0
/***********************************************************************************************************************
* 得到指定地址上的一个字节或字
**********************************************************************************************************************/
#define MEM_B(x) (*((byte *)(x)))
#define MEM_W(x) (*((word *)(x)))
/***********************************************************************************************************************
* 求最大值和最小值
**********************************************************************************************************************/
#define MAX(x,y) (((x)>(y)) ? (x) : (y))
#define MIN(x,y) (((x) < (y)) ? (x) : (y))
/***********************************************************************************************************************
* 得到一个字的高位和低位字节
**********************************************************************************************************************/
#define WORD_LO(xxx) ((byte) ((word)(xxx) & 255))
#define WORD_HI(xxx) ((byte) ((word)(xxx) >> 8))
/***********************************************************************************************************************
* 将一个字母转换为大写
**********************************************************************************************************************/
#define UPCASE(c) (((c)>='a' && (c) <= 'z') ? ((c) – 0×20) : (c))
/***********************************************************************************************************************
* 判断字符是不是10进值的数字
**********************************************************************************************************************/
#define DECCHK(c) ((c)>='0' && (c)<='9')
/***********************************************************************************************************************
* 判断字符是不是16进值的数字
**********************************************************************************************************************/
#define HEXCHK(c) (((c) >= '0' && (c)<='9') ((c)>='A' && (c)<= 'F') \((c)>='a' && (c)<='f'))
/***********************************************************************************************************************
* 防止溢出的一个方法
**********************************************************************************************************************/
#define INC_SAT(val) (val=((val)+1>(val)) ? (val)+1 : (val))
/***********************************************************************************************************************
* 返回数组元素的个数
**********************************************************************************************************************/
#define ARAY_SIZE(array) (sizeof((array))/sizeof((array[0])))
/***********************************************************************************************************************
* 返回一个无符号数n尾的值MOD_BY_POWER_OF_TWO(X,n)=X%(2^n)
**********************************************************************************************************************/
#define MOD_BY_POWER_OF_TWO( val, mod_by ) ((dword)(val) & (dword)((mod_by)-1))
/***********************************************************************************************************************
* 对于IO空间映射在存储空间的结构,输入输出处理
**********************************************************************************************************************/
#define inp(port) (*((volatile byte *)(port)))
#define inpw(port) (*((volatile word *)(port)))
#define inpdw(port) (*((volatile dword *)(port)))
#define outp(port,val) (*((volatile byte *)(port))=((byte)(val)))
#define outpw(port, val) (*((volatile word *)(port))=((word)(val)))
#define outpdw(port, val) (*((volatile dword *)(port))=((dword)(val)))
/***********************************************************************************************************************
* 面向对象
**********************************************************************************************************************/
/* 接口不应当有私有属性 */
#define INTERFACE(sub,super) \
typedef struct sub sub; \
struct sub{ \
super _;
#define PUBLIC(sub,super) \
typedef struct sub sub; \
struct sub{ \
super _; \
struct sub##_P *p;
#define PRIVATE(sub) \
typedef struct sub##_P sub##_P; \
struct sub##_P{
#define PUBLIC_STATIC(sub,super) \
typedef struct sub##ClassType sub##ClassType; \
extern sub##ClassType *const sub##Class; \
struct sub##ClassType{ \
super##ClassType _;
#define PRIVATE_STATIC(sub) \
typedef struct sub##ClassType##_P sub##ClassType##_P; \
struct sub##ClassType##_P{
#if defined(__CLASS_ATTRIBUTE__)
#define STATIC_INIT(sub) \
static void sub##_clinit(); \
static sub##ClassType sub##Clazz[] = { \
{ \
NULL, \
#sub, \
sizeof(sub), \
sizeof(sub##_P), \
offsetof(sub, p), \
sizeof(sub##ClassType), \
REAL, \
false, \
sub##_clinit, \
(void (*)(Object *)) deinit,\
} \
}; \
\
sub##ClassType *const sub##Class = sub##Clazz; \
static void sub##_clinit() {
#define ABSTRACT_STATIC_INIT(sub) \
static void sub##_clinit(); \
static sub##ClassType sub##Clazz[] = { \
{ \
NULL, \
#sub, \
sizeof(sub), \
sizeof(sub##_P), \
offsetof(sub, p), \
sizeof(sub##ClassType), \
ABSTRACT, \
false, \
sub##_clinit, \
(void (*)(Object *)) deinit,\
} \
}; \
\
sub##ClassType *const sub##Class = sub##Clazz; \
static void sub##_clinit() {
#define INTERFACE_STATIC_INIT(sub) \
static void sub##_clinit(); \
static sub##ClassType sub##Clazz[] = { \
{ \
NULL, \
#sub, \
sizeof(sub), \
0, \
0, \
sizeof(sub##ClassType), \
INTERFACE, \
false, \
sub##_clinit, \
NULL,\
} \
}; \
\
sub##ClassType *const sub##Class = sub##Clazz; \
static void sub##_clinit() {
#define FINAL_STATIC_INIT(sub) \
static void sub##_clinit(); \
static sub##ClassType sub##Clazz[] = { \
{ \
NULL, \
#sub, \
sizeof(sub), \
sizeof(sub##_P), \
offsetof(sub, p), \
sizeof(sub##ClassType), \
REAL, \
true, \
sub##_clinit, \
(void (*)(Object *)) deinit,\
} \
}; \
\
sub##ClassType *const sub##Class = sub##Clazz; \
static void sub##_clinit() {
#else
#define STATIC_INIT(sub) \
static void sub##_clinit(); \
static sub##ClassType sub##Clazz[] = { \
{ \
NULL, \
#sub, \
sizeof(sub), \
sizeof(sub##_P), \
offsetof(sub, p), \
sizeof(sub##ClassType), \
sub##_clinit, \
(void (*)(Object *)) deinit,\
} \
}; \
\
sub##ClassType *const sub##Class = sub##Clazz; \
static void sub##_clinit() {
#define ABSTRACT_STATIC_INIT(sub) \
static void sub##_clinit(); \
static sub##ClassType sub##Clazz[] = { \
{ \
NULL, \
#sub, \
sizeof(sub), \
sizeof(sub##_P), \
offsetof(sub, p), \
sizeof(sub##ClassType), \
sub##_clinit, \
(void (*)(Object *)) deinit,\
} \
}; \
\
sub##ClassType *const sub##Class = sub##Clazz; \
static void sub##_clinit() {
#define INTERFACE_STATIC_INIT(sub) \
static void sub##_clinit(); \
static sub##ClassType sub##Clazz[] = { \
{ \
NULL, \
#sub, \
sizeof(sub), \
0, \
0, \
sizeof(sub##ClassType), \
sub##_clinit, \
NULL,\
} \
}; \
\
sub##ClassType *const sub##Class = sub##Clazz; \
static void sub##_clinit() {
#define FINAL_STATIC_INIT(sub) \
static void sub##_clinit(); \
static sub##ClassType sub##Clazz[] = { \
{ \
NULL, \
#sub, \
sizeof(sub), \
sizeof(sub##_P), \
offsetof(sub, p), \
sizeof(sub##ClassType), \
sub##_clinit, \
(void (*)(Object *)) deinit,\
} \
}; \
\
sub##ClassType *const sub##Class = sub##Clazz; \
static void sub##_clinit() {
#endif
#define END } ;
#define IMPLEMENTS(type) struct type type
#define ALLOC(type) alloc((ClassType*)type)
#define EXTEND(sub,super) extend((ClassType*)sub,(ClassType*)super)
#endif //type_H
|
C | #include "adc.h"
#include <avr/io.h>
void adc_setup(void) {
// No interrupts (should be already off)
// The ADC voltage reference is selected by writing the REFS[1:0] bits in the ADMUX register
//ADMUX &= ~(1 << REFS1) & ~(1 << REFS0); // VCC (3.4v) used as analog reference, disconnected from PA0 (AREF)
// The analog input channel is selected by writing to the MUX bits in ADMUX
//ADMUX &= ~(1 << MUX3) & ~(1 << MUX2) & ~(1 << MUX1) & ~(1 << MUX0); // 0000 ADC0 PA3
// ADC Prescaler Select Bits 011 -> 8 so 1MHz / 8 = 125kHz (needs to be under 200kHz for max resolution)
ADCSRA |= (1 << ADPS1) | (1 << ADPS0);
}
uint16_t adc_do_conversion(void) {
// The ADC is enabled by setting the ADC Enable bit, ADEN in ADCSRA
ADCSRA |= (1 << ADEN);
// A single conversion is started by writing a logical one to the ADC Start Conversion bit, ADSC
ADCSRA |= (1 << ADSC);
// This bit stays high as long as the conversion is in progress and will be cleared by hardware when the conversion is completed
// Measured at 206us, which is 1 / 125kHz = 8us * 25 ADC clock cycles = 200us
while (ADCSRA & (1 << ADSC));
// The ADC generates a 10-bit result which is presented in the ADC Data Registers, ADCH and ADCL
// ADCL must be read first, then ADCH
uint16_t level = ADCL;
level |= (uint16_t)(ADCH << 8);
// Turn ADC off
ADCSRA &= ~(1 << ADEN);
return level;
}
|
C | // Questão 6) [SEMANA01_q06.c] Escreva um programa em C que receba um número inteiro o imprima por
// extenso em inglês.
// Entrada: um número inteiro de 0 a 9.
// Saída: Uma linha contendo o número por extenso no idioma inglês
// #include <stdio.h>
// int main(){
// int num;
// scanf("%i",&num);
// switch(num){
// case 0: printf("Nought\n");
// break;
// case 1: printf("One\n");
// break;
// case 2: printf("Two\n");
// break;
// case 3: printf("Three\n");
// break;
// case 4: printf("four\n");
// break;
// case 5: printf("five\n");
// break;
// case 6: printf("six\n");
// break;
// case 7: printf("seven\n");
// break;
// case 8: printf("eight\n");
// break;
// case 9: printf("nine\n");
// break;
// default: printf("Esse caso não encontra-se registrado\n");
// }
// return 0;
// } |
C | #include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <wait.h>
#include <stdlib.h>
int main(int argc, char **argv) {
pid_t pid, werr;
int err;
int status = 0;
if (argc < 2) {
err = printf("error - not enough arguments; usage: %s prog_name\n", argv[0]);
exit(-1);
}
pid = fork();
if (pid == 0) {
execvp(argv[1], &argv[1]);
perror("bad name\n");
exit(-1);
}
else if (pid == -1)
{
perror("can't create child process\n");
exit(-1);
}
if(wait(&status) == -1)
{
perror("waiting for a child failed");
exit(-1);
}
printf("program returned %d\n", WEXITSTATUS(status));
exit(0);
}
|
C | /*
* Copyright (C) 2015 University of Oregon
*
* You may distribute under the terms of either the GNU General Public
* License or the Apache License, as specified in the LICENSE file.
*
* For more information, see the LICENSE file.
*/
/*
*/
/* circ: Approximates object with circle */
#include "imagemath.h"
#include "image_utils.h"
int mathfunc() {
float thr, X, fract;
int pixel, im, r, c, r0, c0, r1, c1, r2, c2, rad, d, dr, dc;
char msg[1024];
if (nbr_infiles<1 || input_sizes_differ || !want_output(0)){
return FALSE;
}
if (nbr_outfiles != in_vec_len[0]) {
sprintf(msg,"object: You must supply as many output images as input images\n");
ib_errmsg(msg);
return FALSE;
}
create_output_files(nbr_infiles, in_object[0]);
fract = 1.0;
if (nbr_params > 0)
fract = in_params[0]/100;
/**************************/
/* Create output images ***/
/**************************/
for (im = 0; im < nbr_infiles; im++){
thr = threshold(in_data[im],img_height,img_width);
find_object(in_data[im],thr,img_height,img_width,
&r0,&c0,&r1,&c1,&r2,&c2,&rad);
printf("Radius is %d\n",rad);
printf("Center is %d,%d\n",r0,c0);
for (r = 0; r < img_height; r++) {
for (c = 0; c < img_width; c++) {
pixel = r*img_width + c;
X = in_data[im][pixel];
dr = (int) (100*100*(r-r0)*(r-r0)/(img_height*img_height));
dc = (int) (100*100*(c-c0)*(c-c0)/(img_width*img_width));
d = (int) sqrt((double) (dr + dc)); /* distance from center */
if ((X > thr) && (d <= rad*fract)) {
out_data[im][pixel] = in_data[im][pixel];
printf("Use pixel (%d, %d) at distance %d (%d, %d)\n",
r,c,d,dr,dc);
}
else
out_data[im][pixel] = 0;
}
}
} /* end image loop */
return TRUE;
}
|
C | #include <stdio.h>
#include <stdlib.h>
/*
Write a program that prints the numbers 1 to 4 on the same line.
Write the program using the following methods.
a) Using one printf statement with no conversion specifiers.
b) Using one printf statement with four conversion specifiers.
c) Using four printf statements.
Exercise 2_17
*/
int main()
{
printf("1 2 3 4\n\n"); //part a
printf("%d %d %d %d\n\n", 1, 2, 3, 4); //part b
printf("1 ");
printf("2 ");
printf("3 ");
printf("4 "); // part c
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* fdf_color.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: pmelodi <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/09/05 21:04:39 by pmelodi #+# #+# */
/* Updated: 2019/09/16 22:04:54 by pmelodi ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/fdf.h"
int color_pnt(t_fdf fdf, int s, int e)
{
if (fdf.curr->color == fdf.cur[e - 1]->color)
return (fdf.curr->color);
if (fdf.curr->x == fdf.cur[s - 1]->x && fdf.curr->y == fdf.cur[s - 1]->y)
return (fdf.cur[s - 1]->color);
if (fdf.curr->x == fdf.cur[e - 1]->x && fdf.curr->y == fdf.cur[e - 1]->y)
return (fdf.cur[e - 1]->color);
return (DEF_COL);
}
int fdf_color_peeks_deflt(int tmp)
{
if (tmp > 0)
return (WHITE);
if (tmp < 0)
return (WINE);
return (ROSE);
}
int fdf_def_col(int z)
{
if (z == 0)
return (ROSE);
if (z > 0 && z <= 3)
return (R_1);
if (z > 3 && z <= 6)
return (R_2);
if (z > 6 && z <= 8)
return (R_3);
if (z > 8 && z <= 10)
return (R_4);
if (z > 10 && z <= 20)
return (R_5);
if (z > 20)
return (WHITE);
return (DARK_R);
}
int fdf_set_color(char *buff, int *len, int z, t_fdf *fdf)
{
int i;
i = 0;
if (buff[i] && (buff[i] == ' ' || buff[i] == '\n'))
{
if (buff[i] == ' ')
*len = 1;
else
*len = 0;
return (fdf_def_col(z));
}
if (buff[i] == ',')
return (fdf_atoi_hex(&(buff[i + 1]), len, fdf));
fdf_error();
return (0);
}
|
C | #include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pwd.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<dirent.h>
#include<errno.h>
#include<string.h>
#include <netdb.h>
#include <sys/param.h>
#include <sys/wait.h>
#include <sys/dir.h>
#include <grp.h>
#include <time.h>
#include <locale.h>
#include <langinfo.h>
#include <stdint.h>
#include <fcntl.h>
#include<signal.h>
void pinfo(char **c)
{
FILE * fp;
char buf1[10000];
char buf2[10000];
int fl,pid;
char name[1000],state;
char name2[1000];
long unsigned int size;
printf("pid ---");
printf("%d\n",getpid() );
printf("Process Status -- ");
if(!c[1] || strcmp(c[1]," ")==0)
{
sprintf(buf1,"/proc/%d/stat",getpid());
sprintf(buf2,"/proc/%d/exe",getpid());
fl=0;
}
else
{
sprintf(buf1,"/proc/%d/stat",c[1]);
sprintf(buf2,"/proc/%d/exe",c[1]);
fl=1;
}
if((fp=fopen(buf1,"r"))!=NULL)
{
fscanf(fp,"%d %*s %c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %lu %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d",&pid,&state,&size);
fclose(fp);
printf("pid -- %d\nProcess Status -- %c\nmemory -- %lu\n",pid,state,size);
if(fl==0)
{
readlink(buf2,name,1000);
printf("Executable Path -- ~/a.out\n");
}
else
{
int number=readlink(buf2,name,1000);
name[number]='\0';
printf("Executable Path -- %s\n",name);
}
}
else
perror("Error");
} |
C | #include <stdio.h>
int main()
{
int a = 2;
int b = 0;
int tic1 = 0;
int tic2 = 0;
int fi[6] = {0, 0, 0, 0, 0, 6};
int ec[7] = {0, 0, 0, 0, 0, 0, 6};
while (a != 0)
{
/* code */
printf("Please type 1 for “first class”\n");
printf("Please type 2 for “economy”\n");
printf("Please type 3 for “exit”\n");
scanf("%d", &b);
switch (b)
{
case 1:
if (fi[tic1] == 0)
{
/* code */
fi[tic1] = 1;
printf("你的座位号为%d\n", tic1+1);
tic1++;
}
else
{
printf("Next Flight leaves in 3 hours\n");
}
break;
case 2:
/* code */
if (ec[tic2]==0)
{
ec[tic2] =1;
/* code */
printf("你的座位号为%d\n", tic2+1);
tic2++;
}
else
{
printf("Next Flight leaves in 3 hours\n");
}
break;
case 3:
a = 0;
break;
default:
printf("error,Please type the correct number\n");
break;
}
}
printf("Program end\n");
} |
C | #define VexNum 10 //顶点个数
#define MAX 36
#define MAXedg 30
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//linux下的清屏函数,windows下是system("clr")
void clrscr()
{
system("clear");
}
typedef enum
{
DG,DN,UDG,UDN
}GaphKind;//{有向图,有向网,无向网}
typedef int AdjMatrix[MAX][MAX]; //邻接矩阵数组
//矩阵图结构体
typedef struct
{
int vexs[MAX]; //顶点向量
AdjMatrix arcs; //邻接矩阵
int vexnum,arcnum;//图的当前顶点数和弧度数
GaphKind kind;//图的种类标志
}Matrix_Graph;
typedef struct vexnode
{
char name[10];
char information[100];
struct edgenode *link;
}vexnode;
typedef struct edgenode
{
int adjvex;
int length;
char info[10];
char info2[100];
struct edgenode *next;
}edgenode, *Node ;
typedef struct Edge
{
int lengh;
int ivex, jvex;
struct Edge *next;
} EdgeType;
typedef struct vertex
{
int num;
char name[10];
}vertex;
typedef struct adjmax
{
vertex vexs[MAX];
int edges[MAX][MAX];
}adjmax;
void Name(int i)
{
switch(i)
{
case 1:
printf("1:行政楼 \n\n");break;
case 2:
printf("2:国家南方林业生态工程实验室 \n\n");break;
case 3:
printf("3:电子信息楼 \n\n");break;
case 4:
printf("图书馆 \n\n");break;
case 5:
printf("体育与艺术馆 \n\n");break;
case 6:
printf("东园体育场 \n\n");break;
case 7:
printf("稻米深加工及副产物国家工程实验室 \n\n");break;
case 8:
printf("文科综合楼 \n\n");break;
case 9:
printf("西园体育场和研究生院楼 \n\n");break;
case 10:
printf("生命科学楼 \n\n");break;
default:
printf("景点编号输入错误!请输入:1-10的数字编号: \n\n");
break;
}
}
void SceneryInformation(int i)
{
switch(i)
{
case 1:
printf("1:行政楼:中南林业科技大学行政楼主要用于迎接外宾和开会及学校的日常管理工作\n\n");break;
case 2:
printf("2:南方林业生态应用技术国家工程实验室:成立于2008年,由国家发改委委托中南林业科技大学进行组建,她的建设对于完善我国南方林业特色技术创新体系,强化林业产业技术原始创新能力,加强林业技术基础研究和产业研发之间的有机衔接,有效整合产学研优势资源,着力提升林业产业核心竞争力和林业生态工程技术的国际竞争力,促进我国南方林业产业发展、生态建设和国家重点工程的技术进步,加速产学研联合、科技成果转化和学科体系建设等诸多方面都有重要意义。\n\n");break;
case 3:
printf("3:电子信息楼:隶属于计算机与信息工程学院,计院的学生主要在这里上实验课,实验设备齐全\n\n");break;
case 4:
printf("图书馆:是中南林业科技大学的标志性建筑,于2007建成,外观漂亮壮观,内部环境宽敞明亮,藏书齐全 \n\n");break;
case 5:
printf("体育与艺术馆:中南林业科技大学的标志性建筑,外观设计洋溢着现代化的气息,可容纳6000多人,是湖南省一流的体育馆,也是中南地区一流的体育馆.2015,承办亚洲男子篮球竞标赛,副比赛场馆,中国羽协比赛 \n\n");break;
case 6:
printf("东园体育场:草坪是真草,日常会有一些业余足球队到这里比赛,晚上会有学生在这跑步 \n\n");break;
case 7:
printf("稻米深加工及副产物国家工程实验室:最近新建的实验室,隶属于食品科学与工程学院,用于稻米深加工及副产物的研究 \n\n");break;
case 8:
printf("文科综合楼:与2013动工,2016建成完工,外观特别壮观,洋溢这现代化的气息,大力的改善了学校的硬件设施,为学生提供了更好的学习条件\n\n");break;
case 9:
printf("西园体育场和研究生院楼:这里主要有足球场,篮球场,网球场,羽毛球场,游泳场,及研究生院楼也在其附近,场地宽阔可供众人娱乐 \n\n");break;
case 10:
printf("生命科学楼:也是林科大的标志性建筑,样子壮观漂亮 \n\n");break;
default:
printf("景点编号输入错误!请输入:1-10的数字编号: \n\n");
break;
}
}
void travgraph(vexnode g[], int n, adjmax adj)//查找指定景点
{
int flag=1,i=1;
int num;
char ch;
printf("\t\t\t 请输入您要查询的景点序号:\n\n");
printf("\t\t\t 1.行政楼 2.南方林业生态应用技术国家工程实验室 3.电子信息楼 4.图书馆 \n\n");
printf("\t\t\t 5.体育与艺术馆 6.东院体育场 7.稻米深加工及副产物国家工程实验室 \n\n");
printf("\t\t\t 8.文科综合楼 9.西园体育场和研究生院楼 10.生命科学楼 \n\n");
printf("你的选择是:");
scanf("%d",&num);
getchar();//清除缓存
printf("该景点的名称是:");
Name(num);
printf("此景店的介绍是:");
SceneryInformation(num);
do{
printf("\t\t 是否继续? Y/N \n");
printf("\t\t 你的选择: ");
scanf("%c",&ch);
getchar();
if(ch=='Y' || ch=='y')
{
clrscr();
flag = 1;
i=1;
printf("\t\t\t 请再次输入您要查询的景点序号: \n\n");
printf("\t\t\t 1.行政楼 2.南方林业生态应用技术国家工程实验室 3.电子信息楼 4.图书馆 \n\n");
printf("\t\t\t 5.体育与艺术馆 6.东院体育场 7.稻米深加工及副产物国家工程实验室 \n\n");
printf("\t\t\t 8.文科综合楼 9.西园体育场和研究生院楼 10.生命科学楼 \n\n");
printf("你的选择是:");
scanf("%d",&num);
getchar();//清除缓存
printf("该景点的名称是:");
Name(num);
printf("此景店的介绍是:");
SceneryInformation(num);
continue;
}
else
{
flag = 0 ;
printf("请再次按回车键返回至主菜单界面");
}
break;
}while(1);
}
void CreateGraph(Matrix_Graph *G) //Matrix_Graph:矩阵图
{//采用数组(邻接矩阵)表示法,构造无向网表
int i , j;
for(i=1;i<=VexNum;i++)
{
G->vexs[i]=i;//构造顶点向量
}
for(i=1;i<=VexNum;i++)//初始化邻接矩阵
for(j=1;j<VexNum;j++) G->arcs[i][j]=0;
G->arcs[1][2]=7;G->arcs[1][4]=20;G->arcs[1][7]=30;
G->arcs[2][1]=7;G->arcs[2][3]=3;G->arcs[2][10]=4;G->arcs[2][4]=12;
G->arcs[2][3]=3;
G->arcs[3][2]=3;G->arcs[3][4]=4;G->arcs[3][5]=9;
G->arcs[3][10]=2;
G->arcs[4][1]=20;G->arcs[4][2]=12;G->arcs[4][3]=4;G->arcs[4][5]=4;
G->arcs[4][6]=1;G->arcs[4][7]=15;G->arcs[4][9]=21;
G->arcs[5][3]=9;G->arcs[5][4]=4; G->arcs[5][6]=2;
G->arcs[5][10]=4;
G->arcs[6][4]=1; G->arcs[6][5]=2;G->arcs[6][7]=23;
G->arcs[7][1]=30;G->arcs[7][4]=15;G->arcs[7][6]=23;G->arcs[7][8]=14;
G->arcs[7][9]=17;
G->arcs[8][7]=14; G->arcs[8][9]=25;
G->arcs[9][4]=21;G->arcs[9][7]=17;G->arcs[9][8]=25;
G->arcs[10][2]=6; G->arcs[10][3]=2; G->arcs[10][4]=2; G->arcs[10][5]=4;
for(i=1;i<VexNum;i++)
for(j=1;j<VexNum;j++)
if(G->arcs[i][j]==0)
G->arcs[i][j]=MAX;
}
void path(Matrix_Graph *G,int s,int e)
{
int i,j,u,c=1,t,v;
int r[VexNum+1][VexNum+1];
int T[VexNum],flag[VexNum],d[VexNum]; //d[N]是权值,因为这是无向网表,一个要被访问正反两次,所以flag[N]是访问次数的标志位
for(i=0;i<=VexNum;i++)
for(j=0;j<=VexNum;j++) r[i][j]=0; //设置空路径
for(i=1;i<=VexNum;i++)
{
T[i]=-1;
flag[i]=1;
d[i]=MAX;
}
flag[s]=0;
while(c<=VexNum)
{
t=MAX;
for(i=1;i<=VexNum;i++)
if(flag[i]&&G->arcs[s][i]<t)
{
t=G->arcs[s][i];v=i;r[v][1]=v;}
for(i=1;i<=c;i++)
for(j=1;j<=VexNum;j++)
if(flag[j]&&d[i]+G->arcs[T[i]][j]<t)//修改权值和路径
{
t=d[i]+G->arcs[T[i]][j];v=j;
if(r[v][0]!=-1)
{
u=1;
while(r[T[i]][u]!=0)
{
r[v][u]=r[T[i]][u];u++;}
}
r[v][u]=v;
}
r[v][0]=-1;
T[c]=v;
flag[v]=0;
d[c]=t;
c++;
}
printf("\n最短路径是以下这条:\n(%d)",s);
j=1;
while(r[e][j]!=0)
{
printf("-->(%d)",r[e][j]);
j++;
}
printf("\n\n");
}
void JieMian()
{
int i,j ;
Matrix_Graph G;
CreateGraph(&G);
int n =0;
vexnode g[MAX];
adjmax adj;
EdgeType e[MAXedg];
char choice ='x';
while(1)
{
clrscr();
printf("\n\n\t\t ***校--园--导--游--图***");
printf("\n\n\t\t --------------------------------------\n\n");
printf("\t\t\t 1.林科大校园地图:\n\n");
printf("\t\t\t 2.林科大景点信息:\n\n");
printf("\t\t\t 3.查找两点间最短路径:\n\n");
printf("\t\t\t 0.退出\n\n");
printf("\n\t\t ---------------------------------------\n\n");
printf("\t\t 中南林业科技大学校训:求实 求新 树木 树人\n\n");
printf("\n\t\t ---------------------------------------\n\n");
printf("\t\t 请输入你的选择(0-3):\n\n");
choice=getchar();
switch(choice)
{
case '1':
clrscr();
printf("\t\t -------林-----科-----大-----地-----图-------- \n\n");
printf(" [5.体育与艺术馆]. \n\n ");
printf(" . . \n\n");
printf(" . . \n\n ");
printf(" . . [3.电子信息楼] \n\n");
printf(" . . . \n\n ");
printf(" . . \n\n");
printf(" . [10.生科楼]. . \n\n ");
printf(" . . \n\n");
printf(" . . . \n\n");
printf(" [6.东园体育场] . \n\n ");
printf(" . . . \n\n ");
printf(" . . \n\n");
printf(" . . . [2.林业工程实验室] \n\n");
printf(" . . . . \n\n ");
printf(" . . . . \n\n");
printf(" .[4.图书馆]. . . . . . . . . . . . [1.行政楼] \n\n");
printf(" . . \n\n");
printf(" . . \n\n");
printf(" . . \n\n");
printf(" . . \n\n");
printf(" [7.稻米深加工实验室]. \n\n");
printf(" . \n\n ");
printf(" . \n\n");
printf(" . \n\n");
printf("[8.文科综合楼]. . . . . . \n\n");
printf(" . . \n\n");
printf(" . . \n\n");
printf(" . . \n\n");
printf(" . . \n\n");
printf(" . . \n\n");
printf(" . . . . . . .[9.西园体育场] \n\n ");
printf("\t\t 请输入任意键返回主菜单");
getchar();
getchar();
break;
case '2':
clrscr();
travgraph(g,n,adj);
getchar();
break;
case '3':
clrscr();
printf("\t\t -----林-----科-----大-----地-----图-----\n\n");
printf(" [5.体育与艺术馆]. \n\n ");
printf(" . . \n\n");
printf(" . . \n\n ");
printf(" . . [3.电子信息楼] \n\n");
printf(" . . . \n\n ");
printf(" . . . \n\n");
printf(" . [10.生科楼]. . \n\n ");
printf(" . . . \n\n");
printf(" . . . \n\n");
printf(" [6.东园体育场] . . \n\n ");
printf(" . . . \n\n ");
printf(" . . . \n\n");
printf(" . . . [2.林业工程实验室] \n\n");
printf(" . . . \n\n ");
printf(" . . . \n\n");
printf(" .[4.图书馆]......................................[1.行政楼] \n\n");
printf(" . . \n\n");
printf(" . . \n\n");
printf(" . . \n\n");
printf(" . . \n\n");
printf(" [7.稻米深加工实验室] \n\n");
printf(" . \n\n ");
printf(" . \n\n");
printf(" . \n\n");
printf("[8.文科综合楼]................... \n\n");
printf(" . . \n\n");
printf(" . . \n\n");
printf(" . . \n\n");
printf(" . . \n\n");
printf(" . . \n\n");
printf(" ..................................[9.西园体育场] \n\n ");
printf("\t\t 你现在的位置是 (请输入1-10的序号): \n");
printf("\t\t\t 1.行政楼 2.南方林业生态应用技术国家工程实验室 3.电子信息楼 4.图书馆 \n\n");
printf("\t\t\t 5.体育与艺术馆 6.东院体育场 7.稻米深加工及副产物国家工程实验室 \n\n");
printf("\t\t\t 8.文科综合楼 9.西园体育场和研究生院楼 10.生命科学楼 \n\n");
printf("\t\t你的输入是: \n");
scanf("%d",&i);
getchar();
printf("\t\t你要去的地方是: (请输入1-10的序号): \n");
printf("\t\t\t 1.行政楼 2.南方林业生态应用技术国家工程实验室 3.电子信息楼 4.图书馆 \n\n");
printf("\t\t\t 5.体育与艺术馆 6.东院体育场 7.稻米深加工及副产物国家工程实验室 \n\n");
printf("\t\t\t 8.文科综合楼 9.西园体育场和研究生院楼 10.生命科学楼 \n\n");
printf("\t\t你的输入是: \n");
scanf("%d",&i);
getchar();
//求最短路径
path(&G ,i ,j);
getchar();
CreateGraph(&G);
do{
printf("是否继续查询: Y/N");
char ch;
int flag=1;
scanf("%c ,&ch");
getchar();
if(ch=='Y' || ch =='y' )
{
flag =1;
i=1;
printf("\2你现在的位置是: (请输入1-10的序号 ): \n");
scanf("%d",&i);
getchar();
printf("\2你要去的地方是: (请输入1-10的序号 ): \n");
scanf("%d",&j);
getchar();
path(&G,i,j);
getchar();
CreateGraph(&G);
continue;
}
else
flag=0;
break;
}while(1);
case '0':
clrscr();
printf("\n\t\t----------------------按任意键退出-----------------------\n\n");
printf("\n\t\t----------------------谢谢您的使用-----------------------\n\n");
getchar();
exit(0);
break;
default:
printf("\n输入有误,请重新输入0-3之间的数字: \n ");
getchar();
break;
}
}
getchar();
}
int main(int argc, char const *argv[])
{
JieMian();
return 0;
}
|
C | int maxArea(int* height, int heightSize) {
int i, j, max, tmp;
i = 0;
j = heightSize - 1;
max = 0;
while(i<j) {
tmp = (height[i]<height[j]?height[i]:height[j]) * (j-i);
if (tmp > max) {
max = tmp;
}
if (height[i] < height[j]) {
i++;
} else {
j--;
}
}
return max;
}
|
C | #include<stdio.h>
#include<math.h>
int decimaltooctal(int decimalnumber);
int main()
{
int decimalnumber,R;
printf("\nenter a decimal no.");
scanf("%d",&decimalnumber);
R=decimaltooctal(decimalnumber);
printf("\noctal of %d =%d",decimalnumber,R);
return 0;
}
int decimaltooctal(int decimalnumber)
{
int octalnumber=0,i=1;
while(decimalnumber=!0)
{
octalnumber=octalnumber+(decimalnumber%8)*i;
decimalnumber=decimalnumber/8;
i=i*10;
}
return octalnumber;
}
|
C | /* Name: main.c
* Author: <insert your name here>
* Copyright: <insert your copyright message here>
* License: <insert your license reference here>
*/
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <util/twi.h>
#include "button.h"
#include "i2cmaster.h"
#include "rtc.h"
// Ports for serial clock, data, and latch.
#define SDA_PORT PORTD
#define CLK_PORT PORTD
#define SDL_PORT PORTD
// Pins for serial clock, data, and latch.
#define SDA_PIN 0
#define CLK_PIN 1
#define SDL_PIN 2
#define RTC_INTERRUPT_PIN 3
#define HOUR_BTN_PIN 4
#define MIN_BTN_PIN 5
#define SEC_BTN_PIN 6
#define TEMP_TOG_BTN_PIN 7
typedef struct digit {
unsigned int a : 1;
unsigned int b : 1;
unsigned int c : 1;
unsigned int d : 1;
unsigned int e : 1;
unsigned int f : 1;
unsigned int g : 1;
unsigned int dp : 1;
} Digit;
// Digit segment configuration for each digit.
Digit zero = {1, 1, 1, 1, 1, 1, 0, 0};
Digit one = {0, 1, 1, 0, 0, 0, 0, 0};
Digit two = {1, 1, 0, 1, 1, 0, 1, 0};
Digit three = {1, 1, 1, 1, 0, 0, 1, 0};
Digit four = {0, 1, 1, 0, 0, 1, 1, 0};
Digit five = {1, 0, 1, 1, 0, 1, 1, 0};
Digit six = {0, 0, 1, 1, 1, 1, 1, 0};
Digit seven = {1, 1, 1, 0, 0, 0, 0, 0};
Digit eight = {1, 1, 1, 1, 1, 1, 1, 0};
Digit nine = {1, 1, 1, 0, 0, 1, 1, 0};
Digit clear = {0, 0, 0, 0, 0, 0, 0, 0};
// A lookup table from actual integer to 7-segment display integer.
Digit* digits[11] = {
&zero,
&one,
&two,
&three,
&four,
&five,
&six,
&seven,
&eight,
&nine,
&clear,
};
volatile uint8_t update_time = 0;
volatile int time[6] = {0, 0, 0, 0, 0, 0};
Button hour_button;
Button min_button;
Button sec_button;
Button temp_toggle_button;
uint8_t holding;
uint8_t show_temp;
#define CLOCK_LOW() (CLK_PORT &= ~(1 << CLK_PIN))
#define CLOCK_HIGH() (CLK_PORT |= 1 << CLK_PIN)
#define DATA_LOW() (SDA_PORT &= ~(1 << SDA_PIN))
#define DATA_HIGH() (SDA_PORT |= 1 << SDA_PIN)
#define LATCH_LOW() (SDL_PORT &= ~(1 << SDL_PIN))
#define LATCH_HIGH() (SDL_PORT |= 1 << SDL_PIN)
void set_digit(int digit_number, int digit_value) {
// Set the clock low to start with.
CLOCK_LOW();
// Also make sure we're not latched.
LATCH_LOW();
// Shift out the digit value data first.
for (int i = 7; i >= 0; --i) {
// Reinterpret our digit struct as an int to pull out each segment's bit.
(*((uint8_t*) digits[digit_value]) & (1 << i)) ? DATA_HIGH() : DATA_LOW();
CLOCK_HIGH();
CLOCK_LOW();
}
// Shift out the digit selector.
for (int i = 7; i >= 0; --i) {
digit_value < 0 ? DATA_LOW() : (i == digit_number) ? DATA_HIGH() : DATA_LOW();
CLOCK_HIGH();
CLOCK_LOW();
}
LATCH_HIGH();
LATCH_LOW();
}
inline void set_time() {
uint8_t sec = 0;
if (!holding) {
if (rtc_read_seconds(&sec) != 0) {
time[4] = time[5] = 9;
} else {
time[4] = sec / 10;
time[5] = sec % 10;
}
}
if (rtc_read_minutes(&sec) != 0) {
time[2] = time[3] = 9;
} else {
time[2] = sec / 10;
time[3] = sec % 10;
}
if (rtc_read_hours(&sec) != 0) {
time[0] = time[1] = 9;
} else {
time[0] = sec / 10;
time[1] = sec % 10;
// If the hours tens place is zero, don't show it at all. We don't want
// it to be 08:00:00, just 8:00:00. However, if both hour digits are
// zero, then we want to show them both.
if (time[0] == 0 && time[1] != 0) {
time[0] = -1;
}
}
if (show_temp) {
if (rtc_read_temp_c(&sec) != 0) {
time[4] = time[5] = 9;
} else {
sec = 32 + (sec * 9.0 / 5.0);
time[4] = sec / 10;
time[5] = sec % 10;
}
}
}
void process_button_input() {
ingest_button_value(&hour_button, (PIND & (1 << HOUR_BTN_PIN)) == 0);
if (is_button_pushed(&hour_button)) {
// They hit the hours button.
rtc_inc_hours();
set_time();
}
ingest_button_value(&min_button, (PIND & (1 << MIN_BTN_PIN)) == 0);
if (is_button_pushed(&min_button)) {
// They hit the mins button.
rtc_inc_mins();
set_time();
}
ingest_button_value(&sec_button, (PIND & (1 << SEC_BTN_PIN)) == 0);
if (is_button_pushed(&sec_button)) {
if (holding) {
// If we were holding, grab the held seconds and set them again.
rtc_set_secs(10 * time[4] + time[5]);
}
holding = !holding;
}
ingest_button_value(&temp_toggle_button,
(PIND & (1 << TEMP_TOG_BTN_PIN)) == 0);
if (is_button_pushed(&temp_toggle_button)) {
show_temp = !show_temp;
set_time();
}
}
int main(void) {
// Make the serial control ports all output pins.
DDRD |= 1 << SDA_PIN;
DDRD |= 1 << CLK_PIN;
DDRD |= 1 << SDL_PIN;
// Set up the hour, minute, and seconds button pins as inputs with the pullup
// enabled.
DDRD &= ~(1 << HOUR_BTN_PIN);
PORTD |= (1 << HOUR_BTN_PIN);
DDRD &= ~(1 << MIN_BTN_PIN);
PORTD |= (1 << MIN_BTN_PIN);
DDRD &= ~(1 << SEC_BTN_PIN);
PORTD |= (1 << SEC_BTN_PIN);
DDRD &= ~(1 << TEMP_TOG_BTN_PIN);
PORTD |= (1 << TEMP_TOG_BTN_PIN);
// Enable interrupts for both rising and falling edges on the RTC interrupt
// pin.
// First we mark the pin as an input pin.
DDRD &= ~(1 << RTC_INTERRUPT_PIN);
// Next we enable the internal pullup.
PORTD |= (1 << RTC_INTERRUPT_PIN);
// The DS3231 has a falling edge of its 1 Hz square wave lined up with second
// changes, so we only trigger on falling edges.
EICRA |= (1 << ISC11);
// Finally, enable INT1.
EIMSK |= (1 << INT1);
// Initialize our i2c interface to talk to the DS3231.
i2c_init();
holding = 0;
show_temp = 0;
sei();
#ifdef SET_TIME
rtc_set_time(10, 17, 5);
#endif
if (rtc_enable_square_wave() != 0) {
return -1;
}
if (rtc_set_24hour(0) != 0) {
return -1;
}
uint8_t button_counter = 0;
while (1) {
if (update_time) {
update_time = 0;
// Because set_time() takes time to fetch the time from the DS3231, the
// last digit in the cycle would be left on for extra time (the normal
// amount of time plus however long it takes to fetch the time from the
// DS3231). This would result it pulsing brighter. To keep it the same
// brightness regardless of whether or not we fetch the time, we disable
// it before fetching the time.
set_digit(5, 10);
set_time();
}
if (++button_counter == 8) {
// Handle any buttons the user is pushing.
// In order to keep the digits on for the same amount of time, we only
// check for button presses every 8th time through the loop.
process_button_input();
button_counter = 0;
}
// Loop through and display all the digits.
for (int i = 0; i < 6; ++i) {
set_digit(i, time[i]);
}
}
return 0;
}
ISR(INT1_vect) {
update_time = 1;
}
|
C |
#include <stdio.h>
#include "gyro.h"
int main()
{
int success = gyro_init();
if (!success) {
return 1;
}
int dx, dy, dz;
int count = 0;
while (1) {
if (gyro_ready()) {
gyro_read(&dx, &dy, &dz);
count++;
if (1) {
printf("%8d %8d %8d %s\n", dx, dy, dz,
gyro_overrun() ? "overrun" : "");
} else {
if (gyro_overrun()) {
printf("overrun (%d)\n", count);
}
}
if (count > 200 && 0) {
break;
}
}
}
return 0;
}
|
C | /*
Q:给定两个数组X和Y,元素都是正数。请找出满足如下条件的数对的数目:
1. x^y > y^x,即x的y次方>y的x次方
2. x来自X数组,y来自Y数组
假设数组X的长度为m,数组Y的长度为n,最直接的暴力法,时间复杂度为O(m*n),但这样的话,并不需要都是正数这个条件的。
那么,我们该如何优化呢?x^y>y^x,对于x和y来讲,有什么规律呢?该如何发现呢?
这里其实有规律的,大多数的条件下,当y>x的时候,x^y>y^x,但是有一些例外,1,2,3,4几个数,需要特殊的考虑,
比如2^4=4^2。这个大家可以通过在纸上写写画画来得到,相对繁琐,我们就不进一步分析了。
我们可否对于原式做一些数学变换呢?使得式子变化简单。如何去做呢?这个式子的复杂体现在两边都是指数的形式,如何变化一下呢?
我们很自然的就想到,逆运算对数运算,则,两边取对数可得:ylog(x)>xlog(y)。
这里同学们可能要问,可以直接取对数么?取对数之后,大小关系仍旧满足么?这里是有两点保证的:
1. 对数函数的性质,单调递增
2. 题目中的说明:元素都是正数
对于式子:ylog(x)>xlog(y),x和y都是正数,则进一步有:两边同时除以xy,则:log(x)/x >log(y)/y。这个式子,看起来也复杂,
但是,x和y都在各自的一边,要简单的多。对于log(x)/x >log(y)/y,
1. 数组X和Y分别计算log(x)/x,log(y)/y
2. 然后对Y进行排序O(nlogn)
3. 遍历X数组,对于每一个x,在Y中,进行二分查找,即可。
总的时间复杂度为O(nlogn + mlogn).
*/
int compare (const void* a, const void* b)
{
return (*(float*)a - *(float*)b);
}
int get_number_pair(int x[], int xlen, int y[], int ylen)
{
int index = 0;
float* px = new float[xlen];
float* py = new float[ylen];
for (index = 0; index < xlen; ++index){
px[index] = log((float)x[index])/x[index];
}
for (index = 0; index < ylen; ++index){
py[index] = log((float)y[index])/y[index];
}
qsort(px, xlen, sizeof(float), compare);
qsort(py, ylen, sizeof(float), compare);
int paire_num = 0;
for (index = 0; index < xlen; ++index){
int left = 0;
int right = ylen;
int mid = 0;
while (left < right){
mid = (left + right) >> 1;
if (px[index] > py[mid]){
if (px[index] < py[mid-1])
break;
else
right = mid - 1;
}else if (px[index] < py[mid]){
if (px[index] > py[mid])
break;
else
left = mid + 1;
}else{
break;
}
}
paire_num += ylen - mid;
}
return paire_num;
}
|
C | #include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include "getline2.h"
int main() {
const int max = 8;
char line[max];
float balance = 0;
while (1) {
printf("Type deposit, check or exit > ");
getline2(line, max);
if (strcmp(line, "deposit") == 0) {
printf("How much? > ");
getline2(line, max);
balance += atof(line);
}
else if (strcmp(line, "check") == 0) {
printf("How much? > ");
getline2(line, max);
balance -= atof(line);
}
else if (strcmp(line, "exit") == 0) {
printf("Bye.\n");
break;
}
printf("Balance: %.2f\n", balance);
}
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* darray_create.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fkante <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/03/02 14:04:30 by fkante #+# #+# */
/* Updated: 2020/03/05 17:34:19 by fkante ### ########.fr */
/* */
/* ************************************************************************** */
#include "darray.h"
#include "libft.h"
t_darray *darray_create(size_t sizeof_elem, size_t init_max)
{
t_darray *array;
array = NULL;
if (init_max > 0)
{
array = ft_memalloc(sizeof(t_darray));
if (array != NULL)
{
array->end = 0;
array->max = init_max;
array->sizeof_elem = sizeof_elem;
array->expand_rate = DEFAULT_EXPAND_RATE;
array->contents = ft_memalloc(init_max * sizeof(void *));
if (array->contents == NULL)
{
darray_destroy(&array);
ft_perror_null(CONTENT_FAIL, __FILE__, __LINE__);
}
}
}
else
ft_perror_null(INITIAL_MAX_ZERO, __FILE__, __LINE__);
return (array);
}
|
C | #include "disk.h"
#include "disk-array.h"
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>
// Global variables
int verbose = 0;
int level, strip, disks, blockSize; //strip is strip size
struct disk_array * diskArray;
// Error Message for input
void errorMsgInput(){
fprintf(stderr, "ERROR IN INPUT\n");
exit(1);
}
// Error Message for parsing
void errorMsgParse(){
fprintf(stderr, "ERROR IN PARSING\n");
exit(1);
}
//Prototypes for functions
void parseLine(char * line);
void readFromArray(int lba, int size);
void writeToArray(int lba, int size, char* buff);
void failDisk(int disk);
void recoverDisk(int disk);
void endProgram();
void getPhysicalBlock(int numberOfDisks, int lba, int* diskToAccess, int* blockToAccess);
int calculateXOR(int diskToSkip, int blockToRead, char* xorBlock);
// Main
int main( int argc, char* argv[]){
// Declarations of variables
char * filename;
char c;
char * endptr;
FILE * fd = 0;
// Make sure number of args is 11 or 12 (verbose optional)
if (argc != 11 && argc != 12){
errorMsgInput();
}
// Structure to keep all command args
static struct option long_options[] =
{
{"level", required_argument, 0, 'a'},
{"strip", required_argument, 0, 'b'},
{"disks", required_argument, 0, 'c'},
{"size", required_argument, 0, 'd'},
{"trace", required_argument, 0, 'e'},
{"verbose", no_argument, 0, 'f'},
{0, 0, 0, 0}
};
int option_index = 0;
while ((c = getopt_long_only(argc, argv, "a:b:c:d:e:f", long_options, &option_index)) != -1) {
switch (c) {
// LEVEL
case 'a':
level = strtol(optarg, &endptr, 10);
// Not an int
if (endptr == optarg){
errorMsgInput();
} else if (level == 0 || level == 10 || level == 4 || level == 5){
//Do not need to do anything
}else { // Not valid RAID number
errorMsgInput();
}
break;
//STRIP
case 'b':
strip = strtol(optarg, &endptr, 10);
// Not an int
if (endptr == optarg){
errorMsgInput();
} else if (strip < 1){ // 0 or negative blocks per strip
errorMsgInput();
}
break;
// DISKS
case 'c':
disks = strtol(optarg, &endptr, 10);
// Not an int
if (endptr == optarg){
errorMsgInput();
} else if (disks < 1){ // 0 or negative disks
errorMsgInput();
}
break;
// SIZE
case 'd':
blockSize = strtol(optarg, &endptr, 10);
// Not an int
if (endptr == optarg){
errorMsgInput();
} else if (blockSize < 1){// 0 or negative blocks per disk
errorMsgInput();
}
break;
// TRACE
case 'e':
filename = malloc(sizeof(char*)*strlen(optarg));
strcpy(filename, optarg);
fd = fopen(filename, "r");
if (fd == 0){
errorMsgInput();
}
break;
// Verbose case
case 'f':
verbose = 1;
break;
// Default
default:
errorMsgInput();
}
}
// Input checking for number of disks vs level
// Check that if it is RAID 10 there are an even # of disks
if ((level == 10) && ((disks % 2) != 0)){
errorMsgInput();
}
// Check that both levels 4 and 5 have more than 2 disks
if (level == 4 && disks < 3){
errorMsgInput();
}
if (level == 5 && disks < 3){
errorMsgInput();
}
// Create a disk array
char * virtualDiskArray = "OurVirutalDisk";
diskArray = disk_array_create(virtualDiskArray, disks, blockSize);
// Gets the line from the trace file
char buf[1000];
while (fgets(buf,1000, fd)!=NULL){
buf[strlen(buf) - 1] = '\0';
parseLine(buf);
}
exit(0);
}
/*
This function will parse the input from the trace file and call the proper function
@param char* line - a line that will be parsed
@return void
*/
void parseLine (char * line){
fprintf(stdout, "%s\n", line);
char* token = strtok(line, " ");
if (token == NULL){
return;
}
char * endPtr;
// Read Command: READ LBA SIZE
if (strcmp(token, "READ") == 0){
//Get the lba
token = strtok(NULL, " ");
if (token == NULL){
errorMsgParse();
}
int lba = strtol(token, &endPtr, 10);
if (token == endPtr) {
errorMsgParse();
}
//Get the size of the read
token = strtok(NULL, " ");
if (token == NULL){
errorMsgParse();
}
int readSize = strtol(token, &endPtr, 10);
if (token == endPtr) {
errorMsgParse();
}
if (token == NULL){
errorMsgParse();
}
//The command should end here
token = strtok(NULL, " ");
if (token != NULL){
errorMsgParse();
}
readFromArray(lba,readSize);
}
// Write command: WRITE LBA SIZE VALUE
else if (strcmp(token, "WRITE") == 0){
//Get the lba
token = strtok(NULL, " ");
if (token == NULL){
errorMsgParse();
}
int lba = strtol(token, &endPtr, 10);
if (token == endPtr) {
errorMsgParse(14);
}
//Get the size of the write
token = strtok(NULL, " ");
if (token == NULL){
errorMsgParse();
}
int writeSize = strtol(token, &endPtr, 10);
if (token == endPtr) {
errorMsgParse();
}
//Get the value to write
token = strtok(NULL, " ");
if (token == NULL){
errorMsgParse();
}
int value = atoi(token);
char buff[BLOCK_SIZE];
int i;
for(i = 0; i < 256; i++){
((int *)buff)[i] = value;
}
//The command should end here
token = strtok(NULL, " ");
if (token != NULL){
errorMsgParse();
}
writeToArray(lba, writeSize, buff);
}
//Fail command: FAIL DISK#
else if (strcmp(token, "FAIL") == 0){
//Get the disk that failed
token = strtok(NULL, " ");
if (token == NULL){
errorMsgParse();
}
int disk = strtol(token, &endPtr, 10);
if (token == endPtr) {
errorMsgParse();
}
//The command should end here
token = strtok(NULL, " ");
if (token != NULL){
errorMsgParse();
}
failDisk(disk);
}
//Recover command: RECOVER DISK#
else if (strcmp(token, "RECOVER") == 0){
//Gert the disk to recover
token = strtok(NULL, " ");
if (token == NULL){
errorMsgParse();
}
int disk = strtol(token, &endPtr, 10);
if (token == endPtr) {
errorMsgParse();
}
//The command should end here
token = strtok(NULL, " ");
if (token != NULL){
errorMsgParse();
}
recoverDisk(disk);
}
// End command: END
else if (strcmp(token, "END") == 0){
//There should be no other arguments with end
token = strtok(NULL, " ");
if (token != NULL){
errorMsgParse();
}
endProgram();
}
else if (strcmp(token, "") == 0){
}
else{
errorMsgParse();
}
}
/*
This function will read from the disk array starting at lba for size
@param int lba - logical block address
@param int size - size of the read
@return void
*/
void readFromArray(int lba, int size){
//Level 0
if (level == 0) {
int currentDisk, currentBlock;
getPhysicalBlock(disks, lba, ¤tDisk, ¤tBlock);
while (size > 0) {
char buffer[BLOCK_SIZE];
// If read succeeds print out the value
if(disk_array_read(diskArray, currentDisk, currentBlock, buffer) == 0){
int* firstValue = (int*)buffer;
fprintf(stdout, "%i ", *firstValue);
}else{
fprintf(stdout, "ERROR ");
}
lba ++;
getPhysicalBlock(disks, lba, ¤tDisk, ¤tBlock);
size --;
}
}
//Level 10
else if(level == 10){
int currentDisk, currentBlock;
getPhysicalBlock(disks, lba, ¤tDisk, ¤tBlock);
currentDisk *= 2;
while (size > 0){
char buffer[BLOCK_SIZE];
// Need to check if 1st disk in mirrored is valid
if (disk_array_read(diskArray, currentDisk, currentBlock, buffer) == 0){
int* firstValue = (int *)buffer;
fprintf(stdout, "%i ", *firstValue);
}
// Need to check if 2nd disk in mirrored is valid
else if (disk_array_read(diskArray, currentDisk + 1, currentBlock, buffer) == 0){
int* firstValue = (int *)buffer;
fprintf(stdout, "%i ", *firstValue);
}
// Otherwise value read
else {
fprintf(stdout, "ERROR ");
}
lba++;
getPhysicalBlock(disks, lba, ¤tDisk, ¤tBlock);
currentDisk *= 2;
size --;
}
}
//Level 4
else if(level == 4){
int currentDisk, currentBlock;
getPhysicalBlock(disks, lba, ¤tDisk, ¤tBlock);
while (size > 0) {
char buffer[BLOCK_SIZE];
// If read succeeds print out value
if(disk_array_read(diskArray, currentDisk, currentBlock, buffer) == 0){
int* firstValue = (int *)buffer;
printf("%i ", *firstValue);
}else{ //Try to recover disk on read fail using parity
if (calculateXOR(currentDisk,currentBlock,buffer) == -1){
printf("ERROR ");
}
else{
int* firstValue = (int *)buffer;
printf("%i ", *firstValue);
}
}
lba ++;
getPhysicalBlock(disks, lba, ¤tDisk, ¤tBlock);
size --;
}
}
//Level 5
else if(level == 5){
int currentDisk, currentBlock;
getPhysicalBlock(disks, lba, ¤tDisk, ¤tBlock);
int currentParityDisk = (currentBlock/strip) % disks;;
if (currentDisk >= currentParityDisk) {
currentDisk ++;
}
while (size > 0) {
char buffer[BLOCK_SIZE];
// If read succeeds print out value
if(disk_array_read(diskArray, currentDisk, currentBlock, buffer) == 0){
int* firstValue = (int *)buffer;
printf("%i ", *firstValue);
}else{ //Try to recover disk on read fail using parity
if (calculateXOR(currentDisk,currentBlock,buffer) == -1){
printf("ERROR ");
}
else{
int* firstValue = (int *)buffer;
printf("%i ", *firstValue);
}
}
lba ++;
getPhysicalBlock(disks, lba, ¤tDisk, ¤tBlock);
currentParityDisk = (currentBlock/strip) % disks;;
if (currentDisk >= currentParityDisk) {
currentDisk ++;
}
size --;
}
}
//Error
else{
errorMsgParse();
}
}
/*
This function will write to the disk array starting at lba, for size, and will write
the pattern in the buff passed into the block
@param int lba - logical block address
@param int size - size of the write
@param char *buff - buffer to write to each block of the disk array
@return void
*/
void writeToArray(int lba, int size, char * buff){
//Level 0
if (level == 0) {
int currentDisk, currentBlock;
getPhysicalBlock(disks, lba, ¤tDisk, ¤tBlock);
//successfulWrite should be 0 after all writing is complete, otherwise print error
//Only want to print error once
int successfulWrite = 0;
while (size > 0) {
successfulWrite += disk_array_write(diskArray, currentDisk, currentBlock, buff);
lba ++;
getPhysicalBlock(disks, lba, ¤tDisk, ¤tBlock);
size --;
}
if (successfulWrite != 0) {
fprintf(stdout, "ERROR ");
}
}
//Level 10
else if(level == 10){
int currentDisk, currentBlock;
getPhysicalBlock(disks, lba, ¤tDisk, ¤tBlock);
currentDisk *= 2;
//successfulWrite should be 0 after all writing is complete
// Only want to print error once
int successfulWrite = 0;
while (size > 0) {
// Status keeps track of if write to disk succeded
// If we fail both, status will equal -2
int status = disk_array_write(diskArray, currentDisk, currentBlock, buff);
status += disk_array_write(diskArray, currentDisk + 1, currentBlock, buff);
if (status == -2){
successfulWrite = -1;
}
lba ++;
getPhysicalBlock(disks, lba, ¤tDisk, ¤tBlock);
currentDisk *= 2;
size--;
}
if (successfulWrite != 0) {
fprintf(stdout, "ERROR ");
}
}
//Level 4
else if(level == 4){
// successfulWrite should be 0 after all writing is complete
// Only want to print error once
int successfulWrite = 0;
int currentDisk, currentBlock;
int stripeLength =(disks - 1)*strip;
int i, j, k;
char temp[BLOCK_SIZE];
char parityChange[BLOCK_SIZE];
while (size > 0) {
int whereInStripe = lba % stripeLength;
int startOfThisStripe = lba - whereInStripe;
int blockOffsetOfThisStripe = (startOfThisStripe)/(disks-1);
int coverTo = whereInStripe + size;
int tempNum;
for(i = 0; i < strip; i ++){
for (j = 0; j < BLOCK_SIZE; j++) {
parityChange[j] = 0;
}
tempNum = i;
//printf("i: %i\n", i);
currentBlock = i + blockOffsetOfThisStripe;
while(tempNum < stripeLength){
//printf("temp: %i\n", tempNum);
currentDisk = tempNum / strip;
if(tempNum >= whereInStripe && tempNum < coverTo){
if (disk_array_write(diskArray, currentDisk, currentBlock, buff)){
successfulWrite --; //write failed
}
for (k = 0; k < BLOCK_SIZE; k++) {
parityChange[k] = parityChange[k] ^ buff[k];
}
}
else{
if (disk_array_read(diskArray, currentDisk, currentBlock, temp) != 0) {
//error reading old data, which means we cannot update parity for this block
}
else{
for (k = 0; k < BLOCK_SIZE; k++) {
parityChange[k] = parityChange[k] ^ temp[k];
}
}
}
tempNum += strip;
}
disk_array_write(diskArray, disks-1, currentBlock, parityChange);
//printf("parity %i is %i\n", i, *((int*)parityChange));
}
int next = startOfThisStripe + stripeLength;
size -= next - lba;
lba = next;
}
if (successfulWrite != 0) {
fprintf(stdout, "ERROR ");
}
}
//Level 5
else if(level == 5){
// successfulWrite should be 0 after all writing is complete
// Only want to print error once
int successfulWrite = 0;
int currentDisk, currentBlock;
int stripeLength =(disks - 1)*strip;
int i, j, k;
int currentParityDisk;
char temp[BLOCK_SIZE];
char parityChange[BLOCK_SIZE];
while (size > 0) {
int whereInStripe = lba % stripeLength;
int startOfThisStripe = lba - whereInStripe;
int blockOffsetOfThisStripe = (startOfThisStripe)/(disks-1);
int coverTo = whereInStripe + size;
int tempNum;
for(i = 0; i < strip; i ++){
for (j = 0; j < BLOCK_SIZE; j++) {
parityChange[j] = 0;
}
tempNum = i;
//printf("i: %i\n", i);
currentBlock = i + blockOffsetOfThisStripe;
currentParityDisk = (currentBlock/strip) % disks;
while(tempNum < stripeLength){
//printf("temp: %i\n", tempNum);
currentDisk = tempNum / strip;
if (currentDisk >= currentParityDisk) {
currentDisk ++;
}
if(tempNum >= whereInStripe && tempNum < coverTo){
if (disk_array_write(diskArray, currentDisk, currentBlock, buff)){
successfulWrite --; //write failed
}
for (k = 0; k < BLOCK_SIZE; k++) {
parityChange[k] = parityChange[k] ^ buff[k];
}
}
else{
if (disk_array_read(diskArray, currentDisk, currentBlock, temp) != 0) {
//error reading old data, which means we cannot update parity for this block
}
else{
for (k = 0; k < BLOCK_SIZE; k++) {
parityChange[k] = parityChange[k] ^ temp[k];
}
}
}
tempNum += strip;
}
disk_array_write(diskArray, currentParityDisk, currentBlock, parityChange);
//printf("parity %i is %i\n", i, *((int*)parityChange));
}
int next = startOfThisStripe + stripeLength;
size -= next - lba;
lba = next;
}
if (successfulWrite != 0) {
fprintf(stdout, "ERROR ");
}
}
//Error
else{
errorMsgParse();
}
}
/*
This function calls provided disk_array_fail_disk method to mark disk as failed
@param int disk - disk to fail
@return void
*/
void failDisk(int disk){
disk_array_fail_disk(diskArray, disk);
}
/*
This function will recover the disk and then attempt to put any recovered data on that
recovered disk
@param int disk - disk to recover
@return void
*/
void recoverDisk(int disk){
// If RAID 0 do nothing besides calling the recover function
disk_array_recover_disk(diskArray, disk);
//Level 10
if (level == 10){
int diskToCopyFrom;
// To determine if recovered disk is first or second in a pair of mirrored disks
if (disk % 2){
diskToCopyFrom = disk - 1;
} else{
diskToCopyFrom = disk + 1;
}
int i;
for (i = 0; i < blockSize; i++){
char buffer[BLOCK_SIZE];
disk_array_read(diskArray, diskToCopyFrom, i, buffer);
disk_array_write(diskArray, disk, i, buffer);
}
}
//Level 4 or 5 do the same attempts at recovery
else if (level == 4 || level == 5){
int i;
char missingData [BLOCK_SIZE];
for (i = 0; i < blockSize; i++){
if(calculateXOR(disk,i, missingData) == -1){
return;
}
disk_array_write(diskArray, disk, i, missingData);
}
}
}
/*
Exit program and print the stats
@params no parameters
@return void
*/
void endProgram(){
disk_array_print_stats(diskArray);
exit(0);
}
/*
Will convert an lba and a number of disks to a disk to access and block to access when
reading and writing
@param int numberOfDisk - number of disks (argument)
@param int lba - logical block address
@param int* diskToAccess - disk to access will be passed by reference
@param int* blockToAccess - block to access will be passed by reference
@return void
*/
void getPhysicalBlock(int numberOfDisks, int lba, int* diskToAccess, int* blockToAccess){
// Level 0
if (level == 0){
*diskToAccess = (lba/strip) % numberOfDisks;
*blockToAccess = (lba%strip)+((lba/strip)/numberOfDisks)*strip;
}
// Level 10
else if (level == 10){
numberOfDisks = numberOfDisks / 2;
*diskToAccess = (lba/strip) % numberOfDisks;
*blockToAccess = (lba%strip)+((lba/strip)/numberOfDisks)*strip;
}
// Level 4
else if (level == 4 || level == 5){
numberOfDisks -= 1;
*diskToAccess = (lba/strip) % numberOfDisks;
*blockToAccess = (lba%strip)+((lba/strip)/numberOfDisks)*strip;
}
}
/*
Calculate the XOR of all the disks besides the one passed at the block given
Return -1 if one of the disks required to calculate the xor is failed or if any invalid arg is passed
the XOR'ed value is returned in the xorBlock, which is assumed to be of size BLOCK_SIZE
As a note, this method uses additive method to calculate the parity bit
@param int diskToSkip - either parity disk or failed disk
@param int blockToRead - which block we want to calculate parity for
@param char *xorBlock - pass by reference the xorBlock that will be used
@return int - 0 on success, -1 on failure
*/
int calculateXOR(int diskToSkip, int blockToRead, char* xorBlock) {
int i;
for (i = 0; i < BLOCK_SIZE; i++) {
xorBlock[i] = 0;
}
//The disk to skip does not exist
if (diskToSkip >= disks) {
return -1;
}
//Check to make sure blockToRead is within range
char temp[BLOCK_SIZE];
for(i=0; i < disks; i++) {
//Skip this diskToSkip
if (i == diskToSkip) {
continue;
}
if (disk_array_read(diskArray, i, blockToRead, temp) != 0) {
return -1;
}
int j;
for (j = 0; j < BLOCK_SIZE; j++) {
xorBlock[j] = xorBlock[j] ^ temp[j];
}
}
return 0;
}
|
C | #include<stdio.h>
int main()
{
int t;
long long int x,y,z,a,n,d,i,term;
scanf("%d",&t);
while(t--)
{
scanf("%lld%lld%lld",&x,&y,&z);
n = (2*z)/(x+y);
d = (y-x)/(n-5);
a = x - (2*d);
printf("%lld\n",n);
for(i=0;i<n;i++)
{
term = a + (i*d);
printf("%lld",term);
if(i!=n-1)
printf(" ");
}
printf("\n");
}
return 0;
}
|
C | /*
** func_hexa_tab.c for corewar asm in /home/meuric_a/CPE_2014_corewar_ODD/asm
**
** Made by Alban Meurice
** Login <[email protected]>
**
** Started on Tue Apr 7 12:04:16 2015 Alban Meurice
** Last update Sun Apr 12 21:51:23 2015 Moisset Raphael
*/
#include <stdlib.h>
#include "my.h"
#include "asm.h"
int **put_in_hexa_tab(int *hexa_line, int **hexa_file)
{
int **cpy;
int x;
x = 0;
if (hexa_file == NULL)
{
if ((hexa_file = malloc(2 * sizeof(int *))) == NULL)
return (my_put_error_null("Can't perform malloc\n"));
hexa_file[0] = hexa_line;
hexa_file[1] = NULL;
return (hexa_file);
}
while (hexa_file[x] != NULL)
x = x + 1;
if ((cpy = malloc((x + 2) * sizeof(int *))) == NULL)
return (my_put_error_null("Can't perform malloc\n"));
x = 0;
while (hexa_file[x] != NULL)
{
cpy[x] = hexa_file[x];
x = x + 1;
}
cpy[x] = hexa_line;
cpy[x + 1] = NULL;
return (cpy);
}
|
C | #include <stdio.h>
#include <stdlib.h>
//#include "iks_grammar.h"
#include "iks_tree.h"
#include "iks_stack.h"
#include "iks_ast.h"
#include "iks_types.h"
static inline void __scope_init(scope_t *scope) {
//scope->st = new_iks_stack();
scope->st = new_iks_dict();
scope->next_addr = 0;
}
scope_t *new_scope() {
scope_t *scope;
scope = malloc(sizeof(scope_t));
__scope_init(scope);
return scope;
}
int verify_coercion(iks_tree_t *id, iks_tree_t *expr) {
int ret=0;
iks_ast_node_value_t *idn,*exprn;
idn = id->item;
exprn = expr->item;
iks_grammar_symbol_t *ids,*exprs;
ids = idn->symbol;
exprs = exprn->symbol;
if(idn->iks_type != exprn->iks_type) {
if((idn->iks_type == IKS_INT)&&(exprn->iks_type == IKS_BOOL)) {
idn->need_coercion=IKS_COERCION_INT_TO_BOOL;
} else if((idn->iks_type == IKS_INT)&&(exprn->iks_type == IKS_FLOAT)) {
//printf("coercion int to float\n");
idn->need_coercion=IKS_COERCION_INT_TO_FLOAT;
} else if((idn->iks_type == IKS_FLOAT)&&(exprn->iks_type == IKS_BOOL)) {
//printf("coercion float to bool\n");
idn->need_coercion=IKS_COERCION_FLOAT_TO_BOOL;
} else if((idn->iks_type == IKS_FLOAT)&&(exprn->iks_type == IKS_INT)) {
//printf("coercion float to int\n");
idn->need_coercion=IKS_COERCION_FLOAT_TO_INT;
} else if((idn->iks_type == IKS_BOOL)&&(exprn->iks_type == IKS_INT)) {
//printf("coercion bool to int\n");
idn->need_coercion=IKS_COERCION_BOOL_TO_INT;
} else if((idn->iks_type == IKS_BOOL)&&(exprn->iks_type == IKS_FLOAT)) {
//printf("coercion bool to float\n");
idn->need_coercion=IKS_COERCION_BOOL_TO_FLOAT;
} else if((exprn->iks_type == IKS_CHAR)) {
if(exprs)
fprintf(stderr,"%d: identificador '%s' conversao impossivel do tipo char\n",exprs->code_line_number,exprs->value);
else fprintf(stderr,"conversao impossivel do tipo char\n");
ret=IKS_ERROR_CHAR_TO_X;
} else if((idn->iks_type != IKS_STRING)&&(exprn->iks_type == IKS_STRING)) {
if(exprs)
fprintf(stderr,"%d: identificador '%s' conversao impossivel do tipo string\n",exprs->code_line_number,exprs->value);
else fprintf(stderr,"conversao impossivel do tipo string\n");
ret=IKS_ERROR_STRING_TO_X;
} else {
if(exprs && ids)
fprintf(stderr,"identificador '%s' e '%s' de tipos incompativeis\n",ids->value,exprs->value);
else fprintf(stderr,"identificadores de tipos incompativeis\n");
ret=IKS_ERROR_WRONG_TYPE;
}
}
return ret;
}
//int verify_function_args(iks_grammar_symbol_t *s, iks_list_t *args) {
// int ret=0;
// iks_grammar_symbol_t *s1,*s2;
// iks_list_t *l1,*l2;
// int sl1,sl2,diff;
// l1 = s->params->next;
// l2 = args->next;
// sl1 = iks_list_size(s->params->next);
// sl2 = iks_list_size(args->next);
// diff = sl1-sl2;
// if (diff!=0) {
// if (sl1>sl2) {
// fprintf(stderr,"faltam %d argumentos em '%s'\n",diff,s->value);
// ret=IKS_ERROR_MISSING_ARGS;
// }
// else {
// fprintf(stderr,"sobram %d argumentos em '%s'\n",diff*-1,s->value);
// ret=IKS_ERROR_EXCESS_ARGS;
// }
// }
// else if (sl1!=0){
// do {
// s1 = l1->item;
// s2 = l2->item;
// if (s1->iks_type!=s2->iks_type) {
// fprintf(stderr,"tipos incompativeis entre '%s' e '%s'\n",s1->value,s2->value);
// ret=IKS_ERROR_WRONG_TYPE_ARGS;
// break;
// }
// l1 = l1->next;
// l2 = l2->next;
// } while(l1 != s->params);
// }
// return ret;
//}
//
//int symbol_is_iks_type(iks_grammar_symbol_t *s,int iks_type) {
// int ret=1;
// //printf("%d vs %d\n",s->iks_type,iks_type);
// if (!(s->iks_type==iks_type)) {
// ret=0;
// }
// return ret;
//}
int infer_type(iks_tree_t *tree1, iks_tree_t *tree2) {
iks_ast_node_value_t *tree1n = tree1->item;
iks_ast_node_value_t *tree2n = tree2->item;
if(tree1n->iks_type == tree2n->iks_type)
return tree1n->iks_type;
if(tree1n->iks_type == IKS_FLOAT) {
int coercion = verify_coercion(tree1, tree2);
if(coercion)
return coercion;
return IKS_FLOAT;
} else if(tree2n->iks_type == IKS_FLOAT) {
int coercion = verify_coercion(tree2, tree1);
if(coercion)
return coercion;
return IKS_FLOAT;
}
if(tree1n->iks_type == IKS_INT) {
int coercion = verify_coercion(tree1, tree2);
if(coercion)
return coercion;
return IKS_INT;
} else if(tree2n->iks_type == IKS_INT) {
int coercion = verify_coercion(tree2, tree1);
if(coercion)
return coercion;
return IKS_INT;
}
}
|
C | #ifndef TRIVARIATE_POLY_H
#define TRIVARIATE_POLY_H
#include "biv_rationalfns.h"
//AS AN IMPORTANT STRAY FROM THE USUAL:
//trivariate polynomials will be defined with coeffs that are !!rational!! bivariate polys...
//wrt to this arctan stuff we're working in K(a,b)[x] so K(a,b) a field should have quotients...
//when we get to using more general trivariate polys, then i'm not certain about how this will work,
//but that bridge and me are a good distance away yet
typedef struct trivariate_poly {
int deg;
biv_rational **brcoefficients;
} tpoly;
//void display_tp();
void free_tp();
void strip_tp();
void free_array_tp();
tpoly *initialize_tp();
tpoly *initialize_and_zero_tp();
tpoly **initialize_array_tp();
tpoly *copy_tp();
tpoly *negative_tp();
tpoly *scale_tp();
tpoly *add_tp();
tpoly *subtract_tp();
tpoly *multiply_tp();
tpoly *one_tp();
tpoly *pow_tp();
//tpoly **pseudo_divide_tp();
bool zero_tp();
bool equals_tp();
biv_rational *content_tp();
//initialize all coefficients to zero
tpoly *initialize_tp(int degree) {
tpoly *trivariate_poly = (tpoly *)calloc(1, sizeof(tpoly));
trivariate_poly->deg = degree;
trivariate_poly->brcoefficients = initialize_array_br(degree+1);
return trivariate_poly;
}
//initialize all coefficients to zero
tpoly *initialize_and_zero_tp(int degree) {
int i;
tpoly *trivariate_poly = (tpoly *)calloc(1, sizeof(tpoly));
bpoly *onebp = one_bp();
field_extension *zero = initialize_and_zero_fe(0);
field_extension *onefe = bp_to_fe(onebp);
biv_rational *zerobr = init_br(zero, onefe);
trivariate_poly->deg = degree;
trivariate_poly->brcoefficients = initialize_array_br(degree+1);
for(i=0; i<=degree; ++i) {
trivariate_poly->brcoefficients[i] = copy_br(zerobr);
}
free_br(zerobr);
free_fe(onefe);
free_bp(onebp);
free_fe(zero);
return trivariate_poly;
}
//initialize an array of n zero trivariate polynomisls
tpoly **initialize_array_tp(int n) {
tpoly **array_tp = (tpoly **)calloc(n, sizeof(tpoly *));
return array_tp;
}
//copy tp
tpoly *copy_tp(tpoly *t_poly1) {
int i;
tpoly *duplicate = (tpoly *)calloc(1, sizeof(tpoly));
duplicate->deg = t_poly1->deg;
duplicate->brcoefficients = (biv_rational **)
calloc(duplicate->deg+1, sizeof(biv_rational *));
for(i=0; i<=t_poly1->deg; ++i) {
duplicate->brcoefficients[i] = copy_br(t_poly1->brcoefficients[i]);
}
return duplicate;
}
//free trivariate poly
void free_tp(tpoly *t_poly) {
for(int i=0; i<=t_poly->deg; ++i) {
free_br(t_poly->brcoefficients[i]);
}
free(t_poly->brcoefficients);
free(t_poly);
}
void free_array_tp(tpoly **tpolyarray, int len) {
for(int i=0; i<len; ++i) {
free_tp(tpolyarray[i]);
}
free(tpolyarray);
}
//check if trivariate poly is zero
bool zero_tp(tpoly *t_poly) {
int i;
bool result = true;
for(i=0; i<=t_poly->deg; ++i) {
if(!zero_fe(t_poly->brcoefficients[i]->num)) {
result = false;
}
}
return result;
}
//strip trivariate poly of higher order terms with zero coeffs
void strip_tp(tpoly *t_poly) {
int i, leading_zeroes=0, degree;
if(zero_tp(t_poly)) {
biv_rational **new_coeffs = (biv_rational **)calloc(1, sizeof(biv_rational *));
new_coeffs[0] = copy_br(t_poly->brcoefficients[0]);
for(i=0; i<=t_poly->deg; ++i) {
free_br(t_poly->brcoefficients[i]);
}
free(t_poly->brcoefficients);
t_poly->deg = 0;
t_poly->brcoefficients = new_coeffs;
}
else {
while(zero_fe(t_poly->brcoefficients[leading_zeroes]->num)) {
++leading_zeroes;
}
degree = t_poly->deg-leading_zeroes;
biv_rational **new_coeffs = (biv_rational **)
calloc(degree+1, sizeof(biv_rational *));
for(i=0; i<=degree; ++i) {
new_coeffs[i] = copy_br(t_poly->brcoefficients[i + leading_zeroes]);
}
for(i=0; i<=t_poly->deg; ++i) {
free_br(t_poly->brcoefficients[i]);
}
free(t_poly->brcoefficients);
t_poly->deg = degree;
t_poly->brcoefficients = new_coeffs;
}
}
//negate a trivariate polynomial
tpoly *negative_tp(tpoly *t_poly) {
int i;
tpoly *result;
result = initialize_tp(t_poly->deg);
for(i=0; i<=t_poly->deg; ++i) {
result -> brcoefficients[i] = negative_br(t_poly->brcoefficients[i]);
}
return result;
}
tpoly *scale_tp(biv_rational *scalar, tpoly *poly) {
int i;
tpoly *result = initialize_tp(poly->deg);
for(i=0; i<= poly->deg; ++i) {
result->brcoefficients[i] = multiply_br(scalar, poly->brcoefficients[i]);
}
return result;
}
//add two polys
tpoly *add_tp(tpoly *t_poly1, tpoly *t_poly2) {
int i, difference;
tpoly *result;
if(t_poly1->deg < t_poly2->deg) {
result = add_tp(t_poly2, t_poly1);
}
else {
difference = t_poly1->deg - t_poly2->deg;
result = initialize_tp(t_poly1->deg);
for(i=0; i<difference; ++i) {
result->brcoefficients[i] = copy_br(t_poly1->brcoefficients[i]);
}
for(i=difference; i<=result->deg; ++i) {
result->brcoefficients[i] =
add_br(t_poly1->brcoefficients[i], t_poly2->brcoefficients[i-difference]);
}
}
strip_tp(result);
return result;
}
//subtract two polys
tpoly *subtract_tp(tpoly *t_poly1, tpoly *t_poly2) {
tpoly *result;
result = add_tp(t_poly1, negative_tp(t_poly2));
return result;
}
//multiplication
tpoly *multiply_tp(tpoly *t_poly1, tpoly *t_poly2) {
int i,j;
tpoly *result;
result = initialize_and_zero_tp(t_poly1->deg +t_poly2->deg);
for(i=0; i<=t_poly1->deg; ++i) {
for(j=0; j<= t_poly2->deg; ++j) {
result->brcoefficients[i+j] =
add_br(result->brcoefficients[i+j], multiply_br(t_poly1->
brcoefficients[i], t_poly2->brcoefficients[j]));
}
}
strip_tp(result);
return result;
}
//make one t poly
tpoly *one_tp() {
tpoly *onetp;
bpoly *onebp = one_bp();
onetp = initialize_tp(0);
biv_rational *one= init_br(bp_to_fe(onebp), bp_to_fe(onebp));
onetp->brcoefficients[0] = copy_br(one);
free_bp(onebp);
free_br(one);
return onetp;
}
//raises a trivariate polynomial to the power of an int
tpoly *pow_tp(tpoly *t_poly1, int exp) {
if(exp==0) {
tpoly *onetp = one_tp();
return onetp;
}
else if(exp==1) {
return t_poly1;
}
else {
return multiply_tp(pow_tp(t_poly1, exp-1), t_poly1);
}
}
//remember importantly that we are working over something like K(a,b)[x]
tpoly **divide_tp(tpoly *t_poly1, tpoly *t_poly2) {
tpoly **result = initialize_array_tp(2);
if(zero_tp(t_poly2)) {
printf("Error: division by zero polynomial\n");
exit(0);
}
else {
int d=0;
biv_rational *t;
tpoly *division, *newquo, *newrem;
tpoly *quotient = initialize_and_zero_tp(0);
tpoly *remainder = copy_tp(t_poly1);
while(!zero_tp(remainder) && (remainder->deg - t_poly2->deg)>=0) {
d = remainder->deg - t_poly2->deg;
t = divide_br(remainder->brcoefficients[0], t_poly2->brcoefficients[0]);
division = initialize_and_zero_tp(d);
division->brcoefficients[0] = copy_br(t);
newquo = add_tp(quotient, division);
free_tp(quotient);
quotient = newquo;
newrem = subtract_tp(remainder, multiply_tp(t_poly2, division));
free_tp(remainder);
remainder = newrem;
free_br(t);
free_tp(division);
}
result[0] = quotient;
result[1] = remainder;
}
return result;
}
//half extended euclidean algorithm in K(a,b)[x]
tpoly **half_ext_euclid_tp(tpoly *t_poly1, tpoly *t_poly2) {
tpoly **result;
tpoly *a, *b;
tpoly *q, *r, *a_1, *b_1, *r_1;
a_1 = one_tp();
b_1 = initialize_and_zero_tp(0);
a = copy_tp(t_poly1);
b = copy_tp(t_poly2);
while(!zero_tp(b)) {
q = divide_tp(a, b)[0];
r = divide_tp(a, b)[1];
free_tp(a);
a = copy_tp(b);
free_tp(b);
b = copy_tp(r);
r_1 = subtract_tp(a_1, multiply_tp(q, b_1));
free_tp(a_1);
a_1 = copy_tp(b_1);
free_tp(b_1);
b_1 = copy_tp(r_1);
free_tp(r_1);
free_tp(q);
free_tp(r);
}
result = initialize_array_tp(2);
result[0] = a_1;
result[1] = a;
free_tp(b_1);
free_tp(b);
return result;
}
//full extended euclidean algorithm in K(a,b)[x]
//returns S,T,G, st G=gcd(t_poly1, t_poly2) and G = St_poly1 +Tt_poly2
tpoly **ext_euclid_tp(tpoly *t_poly1, tpoly *t_poly2) {
tpoly *s, *g, *t, *r;
tpoly **result;
s = half_ext_euclid_tp(t_poly1, t_poly2)[0];
g = half_ext_euclid_tp(t_poly1, t_poly2)[1];
t = divide_tp(subtract_tp(g, multiply_tp(s, t_poly1)), t_poly2)[0];
// r = divide_tp(subtract_tp(g, multiply_tp(s, t_poly1)), t_poly2)[1]; //r must be zero
result = initialize_array_tp(3);
result[0] = s;
result[1] = t;
result[2] = g;
return result;
}
bool equals_tp(tpoly *t_poly1, tpoly *t_poly2) {
return zero_tp(subtract_tp(t_poly1, t_poly2));
}
biv_rational *content_tp(tpoly *t_poly) {
return gcd_array_br(t_poly->deg, t_poly->brcoefficients);
}
#endif /* TRIVARIATE_POLY_H */
|
C | #include "philo.h"
void free_clean_mutex(t_all *all, t_philo *philos)
{
int i;
i = 0;
while (i < all->nb_of_philos)
{
pthread_join(philos[i].philo_thread, NULL);
i++;
}
i = 0;
while (i < all->nb_of_philos)
{
pthread_mutex_destroy(&all->forks[i]);
i++;
}
pthread_mutex_destroy(&all->phrase);
pthread_mutex_destroy(&all->manger);
pthread_mutex_destroy(&all->mourir);
free(all->forks);
free(philos);
}
int values_of_args(t_all *all, int argc, char *argv[])
{
int i;
i = 1;
all->each_must_eat = -1;
while (argv[i])
{
if (ft_is_str_number(argv[i]))
return (ft_error("Error: No numbers\n"));
i++;
}
all->nb_of_philos = ft_atoi(argv[1]);
all->time_to_die = ft_atoi(argv[2]);
all->time_to_eat = ft_atoi(argv[3]);
all->time_to_sleep = ft_atoi(argv[4]);
if (argc == 6)
all->each_must_eat = ft_atoi(argv[5]);
return (0);
}
int verif_values_of_args(t_all *all, int argc)
{
if (all->nb_of_philos <= 0)
return (ft_error("Error: number of philos\n"));
if (all->time_to_die < 0)
return (ft_error("Error: time to die\n"));
if (all->time_to_eat < 0)
return (ft_error("Error: time to eat\n"));
if (all->time_to_sleep < 0)
return (ft_error("Error: time to sleep\n"));
if (argc == 6 && all->each_must_eat <= 0)
return (ft_error("Error: num of each must eat\n"));
return (0);
}
int main(int argc, char *argv[])
{
t_all all;
t_philo *philos;
if (argc != 5 && argc != 6)
{
printf("Error with number of arguments\n");
return (1);
}
if (values_of_args(&all, argc, argv))
return (1);
if (verif_values_of_args(&all, argc))
return (1);
if (table_of_philos(&all, philos))
return (1);
philos = malloc(sizeof(t_philo) * (all.nb_of_philos));
if (philos == NULL)
return (ft_error("Error: malloc failed\n"));
init_philos(&all, philos);
free_clean_mutex(&all, philos);
return (0);
}
|
C | int main()
{
int n,i;
int m[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
scanf("%d",&n);
for(i=0;i<7;i++)
{
if((n+i)%7==5)
{
n=(1+i)%7;//??????
break;
}
}
//printf("first Friday=%d\n",n);
int e=13;
for(i=0;i<12;i++)
{
e=e+m[i];
//printf("%d\n",e);
if(e%7==n)
{
printf("%d\n",i+1);
}
}
return 0;
} |
C | #include <stdio.h>
void print_largest_two(int *array,int size){
int largest01 = 0;
int largest02 = 0;
for (int i = 0 ; i < size; i++){
if(array[i] > array[i+1]){
largest01 = array[i];
}
if(array[i+1] > array[i]){
largest01 = array[i+1];
}
}
printf("%d",largest01);
}
int main(void) {
{
int numbers[] = {13, 5, 6, 11};
printf("Test 1\n");
printf("Expected:#1 = 13, #2 = 11\n");
printf("Actual :");
print_largest_two(numbers, sizeof(numbers) / sizeof(int));
printf("\n");
}
{
int numbers[] = {13, 13, 6, 11};
printf("Test 2\n");
printf("Expected:#1 = 13, #2 = 13\n");
printf("Actual :");
print_largest_two(numbers, sizeof(numbers) / sizeof(int));
printf("\n");
}
{
int numbers[] = {13, 11, 1, 8, 2, 3, 5, 6, 6, 13};
printf("Test 3\n");
printf("Expected:#1 = 13, #2 = 13\n");
printf("Actual :");
print_largest_two(numbers, sizeof(numbers) / sizeof(int));
printf("\n");
}
{
int numbers[] = {13, 11, 1, 8, 2, 3, 5, 6, 6, 17};
printf("Test 4\n");
printf("Expected:#1 = 17, #2 = 13\n");
printf("Actual :");
print_largest_two(numbers, sizeof(numbers) / sizeof(int));
printf("\n");
}
{
int numbers[] = {21, 11, 1, 8, 2, 3, 5, 6, 6, 17};
printf("Test 1\n");
printf("Expected:#1 = 21, #2 = 17\n");
printf("Actual :");
print_largest_two(numbers, sizeof(numbers) / sizeof(int));
printf("\n");
}
{
int numbers[] = {1, 2};
printf("Test 1\n");
printf("Expected:#1 = 2, #2 = 1\n");
printf("Actual :");
print_largest_two(numbers, sizeof(numbers) / sizeof(int));
printf("\n");
}
{
int numbers[] = {1};
printf("Test 1\n");
printf("Expected:#1 = 1\n");
printf("Actual :");
print_largest_two(numbers, sizeof(numbers) / sizeof(int));
printf("\n");
}
} |
C | //*****************************************************************************
// Luke Hsiao
// 4 May 2015
// Interface for displaying the clock
//
// Details:
// Note that the area of the touchscreen will be displayed and scaled usering
// these regions:
// +--+---+---+---+---+---+---+---+---+--+
// | | | | | | | | | | |
// +--+===+===+===+===+===+===+===+===+--+
// | | /\ | | /\ | | /\ | |
// +--+---+---+---+---+---+---+---+---+--+
// | | H | H | : | M | M | : | S | S | |
// +--+---+---+---+---+---+---+---+---+--+
// | | \/ | | \/ | | \/ | |
// +--+===+===+===+===+===+===+===+===+--+
// | | | | | | | | | | |
// +--+---+---+---+---+---+---+---+---+--+
//*****************************************************************************
#include <stdbool.h>
//*****************************************************************************
// User Editable Macros:
// Edit this to change the size of the clock chars. Only set this value to
// 3, 4, 5, or 6. Otherwise, the clock will NOT display correctly.
#define CLOCKDISPLAY_CLOCK_TEXT_SIZE 4
// Values to Initialize clock to on startup
#define CLOCKDISPLAY_INITIAL_HOURS 12
#define CLOCKDISPLAY_INITIAL_MINUTES 59
#define CLOCKDISPLAY_INITIAL_SECONDS 55
//***************** End User Editable Macros **********************************
// Region IDs for the touchscreen
#define CLOCKDISPLAY_REGION_0 0
#define CLOCKDISPLAY_REGION_1 1
#define CLOCKDISPLAY_REGION_2 2
#define CLOCKDISPLAY_REGION_3 3
#define CLOCKDISPLAY_REGION_4 4
#define CLOCKDISPLAY_REGION_5 5
#define CLOCKDISPLAY_REGION_ERR -1
// Constants for calculating time rollovers
#define CLOCKDISPLAY_MAX_SECS 59
#define CLOCKDISPLAY_MAX_MINS 59
#define CLOCKDISPLAY_MAX_HRS 12 // Since we're displaying a 12-hr clock
//*****************************************************************************
// Because the size of the arrows and clock characters are scaled based on
// CLOCK_TEXT_SIZE, the macros below perform all of the necessary scaling
// calculations.
#define CLOCKDISPLAY_SCALE_TEXT 7 // Value used to scale the clock text
// BUFFER represents the spacing between the drawn characters and the
// edges of their designated boxes.
#define CLOCKDISPLAY_BUFFER (CLOCKDISPLAY_CLOCK_TEXT_SIZE * 2)
#define CLOCKDISPLAY_HALF(X) ((X) / 2) // divide the input by 2
#define CLOCKDISPLAY_THIRD(X) ((X) / 3) // divide the input by 3
#define CLOCKDISPLAY_EIGHTH(X) ((X) / 8) // divide the input by 8
#define CLOCKDISPLAY_NUM_COLS 9 // number of columns to divide the display into.
#define CLOCKDISPLAY_NUM_ROWS 4 // number of rows to divide the display into.
#define CLOCKDISPLAY_NUM_CHARS 9 // 8 chars for "HH:MM:SS" + 1 for '\0'
// Macros for names of the indexes in the char arrays
#define CLOCKDISPLAY_TENS_HRS 0
#define CLOCKDISPLAY_ONES_HRS 1
#define CLOCKDISPLAY_COLON_1 2
#define CLOCKDISPLAY_TENS_MINS 3
#define CLOCKDISPLAY_ONES_MINS 4
#define CLOCKDISPLAY_COLON_2 5
#define CLOCKDISPLAY_TENS_SECS 6
#define CLOCKDISPLAY_ONES_SECS 7
// Macros for making calls to updateTimeDisplay(bool X) more readable
#define CLOCKDISPLAY_UPDATE_ALL true // force update all
#define CLOCKDISPLAY_DO_NOT_UPDATE_ALL false // do not force update all
// Time macros used in runTest() in units of milliseconds
#define CLOCKDISPLAY_TENTH_SECOND 100
#define CLOCKDISPLAY_HALF_SECOND 500
#define CLOCKDISPLAY_TENTHS_IN_TEN_SECONDS 100 // # of 100ms in 10 seconds
/**
* Initializes the clock display. Should only be called once.
*/
void clockDisplay_init();
/**
* Updates the time display with the latest time.
* @param forceUpdateAll If true, refreshes ALL characters rather than just
* the ones that are being updated.
*/
void clockDisplay_updateTimeDisplay(bool forceUpdateAll);
/**
* Performs and Increment or decrement depending on which region of the
* touchscreen is being pressed.
*/
void clockDisplay_performIncDec();
/**
* Advances the time forward by 1 second.
*/
void clockDisplay_advanceTimeOneSecond();
/**
* Runs a test that allows a user to visually verify correct clock-display
* functionality. This function performs the following operations:
* 1. Increments Hours
* 2. Decrements Hours
* 3. Increments Minutes
* 4. Decrements Minutes
* 5. Increments Seconds
* 6. Decrements Seconds
* 7. Show the clock keeping time at a a 10x rate for 10 real-world seconds
*/
void clockDisplay_runTest();
|
C | //
// quicksort.h
// lab11
//
// Created by zwpdbh on 8/16/16.
// Copyright © 2016 Otago. All rights reserved.
//
#ifndef quicksort_h
#define quicksort_h
#include <stdio.h>
extern void quicksort(int *arr, int lowIndex, int highIndex);
int partition(int *arr, int lowIndex, int hightIndex);
void swap(int *x, int *y);
#endif /* quicksort_h */
|
C | #include<stdio.h>
#include<conio.h>
void main()
{
int inter;
float p,r,n;
clrscr();
printf("Enter principle amount:\n");
scanf("%f",&p);
printf("Enter no.of years:\n");
scanf("%f",&n);
printf("Enter rate of interest:\n");
scanf("%f",&r);
inter=(p*n*r)/100;
printf("Simple Interest=%d",inter);
getch();
}
|
C | /*
BATCH NO. 27
Mayank Agarwal (2014A7PS111P)
Karan Deep Batra(2014A7PS160P)
*/
#include <stdlib.h>
#include <string.h>
#include "token.h"
tokeninfo* makeToken(char* tokenname, char* lexeme, int linenumber)
{
tokeninfo* temp = (tokeninfo*)malloc(sizeof(tokeninfo));
int l = strlen(tokenname);
temp->tokenname = (char*)malloc((l+1)* (sizeof(char)));
strcpy(temp->tokenname, tokenname);
l = strlen(lexeme);
temp->lexeme = (char*)malloc((l+1)* (sizeof(char)));
strcpy(temp->lexeme, lexeme);
temp->linenumber = linenumber;
temp->next = NULL;
return temp;
}
|
C | #include "xsal.h"
#include "xsal_i_assert.h"
#include "xsal_i_time.h"
#include "xsal_i_message_queue.h"
SAL_Message_T* SAL_I_Pend_Message_Timeout(
SAL_Message_Queue_T* queue,
uint32_t timeout_ms)
{
SAL_I_Time_Spec_T time1;
bool wait_for_msg = true;
SAL_Message_Queue_Node_T* msg;
SAL_Message_Queue_Node_T* end_marker;
SAL_PRE(queue != NULL);
SAL_PRE(queue->node_tab != NULL);
end_marker = queue->end_marker;
SAL_I_Get_Time(&time1);
do
{
if (SAL_Wait_Semaphore_Timeout(&queue->message_available, timeout_ms))
{
if (SAL_Lock_Mutex(&queue->queue_lock))
{
msg = end_marker->next_node;
if (msg != end_marker)
{
SAL_I_Remove_Node_From_Queue(msg);
wait_for_msg = false;
}
else
{
uint32_t diff;
SAL_I_Time_Spec_T time2;
SAL_I_Get_Time(&time2);
diff = SAL_I_Time_Diff(&time1, &time2);
if (diff < timeout_ms)
{
timeout_ms -= diff;
time1 = time2;
}
else
{
/** Set msg to NULL and exit
*/
wait_for_msg = false;
msg = NULL;
}
}
(void)SAL_Unlock_Mutex(&queue->queue_lock);
}
else
{
wait_for_msg = false;
msg = NULL;
SAL_PRE_FAILED();
}
}
else
{
/** Set msg to NULL and exit
*/
wait_for_msg = false;
msg = NULL;
}
} while(wait_for_msg);
return (SAL_Message_T*)(void*)msg;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <stdint.h>
#include <string.h>
#define CHECK_ERROR(condition,message) \
do {if (condition) { \
fprintf(stderr, "%s:%d:%s: %s\n",__FILE__,__LINE__,__func__,message); \
exit(EXIT_FAILURE); \
}}while(0)
#define CHECK_ERRNO(condition, message) \
do {if (condition) { \
fprintf(stderr, "%s:%d:%s:%s: ",__FILE__,__LINE__,__func__,message); \
fflush(stderr); \
perror(NULL); \
exit(EXIT_FAILURE); \
}}while(0)
#define CHECK_FILE(condition,file,message) \
do {if (condition) { \
fprintf(stderr, "%s:%d:%s:%s: ",__FILE__,__LINE__,__func__,message); \
fflush(stderr); \
if (feof(file)) { \
fprintf(stderr,"unexpected EOF\n"); \
} else { \
perror(message); \
} \
exit(EXIT_FAILURE); \
}}while(0)
void update(FILE *infile, long old_length, long new_length);
uint32_t read_32_le(unsigned char bytes[4]);
uint16_t read_16_le(unsigned char bytes[2]);
int main(int argc, char **argv)
{
CHECK_ERROR(argc != 3, "add_silence 0.0 - add silent frames from the end of 44.1khz PCM WAV\n\nIncorrect program usage\n\nusage: strip_silence input.wav bytes)");
long add_bytes;
add_bytes = atol(argv[2]);
/* open file */
FILE *infile = fopen(argv[1], "r+b");
CHECK_ERRNO(!infile, "fopen");
/* get file size */
CHECK_ERRNO(fseek(infile, 0 , SEEK_END) != 0, "fseek");
long file_length = ftell(infile);
CHECK_ERRNO(file_length == -1, "ftell");
rewind(infile);
update(infile, file_length, file_length+add_bytes);
CHECK_ERRNO(fclose(infile) != 0, "fclose");
exit(EXIT_SUCCESS);
}
uint32_t read_32_le(unsigned char bytes[4])
{
uint32_t result = 0;
for (int i=3; i>=0; i--) result = (result << 8) | bytes[i];
return result;
}
uint16_t read_16_le(unsigned char bytes[2])
{
uint32_t result = 0;
for (int i=1; i>=0; i--) result = (result << 8) | bytes[i];
return result;
}
void write_32_le(unsigned char bytes[4], uint32_t v)
{
for (int i=0; i<4; i++)
{
bytes[i] = v & 0xff;
v >>= 8;
}
}
void write_16_le(unsigned char bytes[2], uint32_t v)
{
for (int i=0; i<2; i++)
{
bytes[i] = v & 0xff;
v >>= 8;
}
}
void update(FILE *infile, long old_length, long new_length)
{
unsigned char buf[4];
size_t bytes_read;
size_t bytes_written;
CHECK_ERROR(
!(new_length >= old_length && (new_length-old_length)%4 == 0),
"internal error (bad size for update)");
/* check old RIFF length */
CHECK_ERRNO(fseek(infile, 0x04, SEEK_SET) != 0, "fseek");
bytes_read = fread(buf, 1, 4, infile);
CHECK_FILE(bytes_read != 4, infile, "fread");
CHECK_ERROR(read_32_le(buf)+8 != old_length, "RIFF size doesn't check out (extra chunks?)\n");
/* check old data length */
CHECK_ERRNO(fseek(infile, 0x28, SEEK_SET) != 0, "fseek");
bytes_read = fread(buf, 1, 4, infile);
CHECK_FILE(bytes_read != 4, infile, "fread");
CHECK_ERROR(read_32_le(buf)+0x2c != old_length, "data size doesn't check out (extra chunks?)\n");
/* update RIFF length */
CHECK_ERRNO(fseek(infile, 0x04, SEEK_SET) != 0, "fseek");
write_32_le(buf, new_length-8);
bytes_written = fwrite(buf, 1, 4, infile);
CHECK_FILE(bytes_written != 4, infile, "fwrite");
/* update data length */
CHECK_ERRNO(fseek(infile, 0x28, SEEK_SET) != 0, "fseek");
write_32_le(buf, new_length-0x2c);
bytes_written = fwrite(buf, 1, 4, infile);
CHECK_FILE(bytes_written != 4, infile, "fwrite");
/* append silence */
long offset = old_length;
write_16_le(buf, 0);
write_16_le(buf+2, 0);
CHECK_ERRNO(fseek(infile, offset, SEEK_SET) != 0, "fseek");
while (offset < new_length)
{
bytes_written = fwrite(buf, 1, 4, infile);
CHECK_FILE(bytes_written != 4, infile, "fwrite");
offset += 4;
}
}
|
C | #include <stdio.h>
#include <string.h>
int main() {
char A[101], B[201];
int i, j;
gets(A);
for (j = 0,i = 0; i < strlen(A); ++i) {
putchar(A[i]);
switch(A[i]) {
case 'a' : { printf("pa"); } break;
case 'i' : { printf("pi"); } break;
case 'u' : { printf("pu"); } break;
case 'e' : { printf("pe"); } break;
case 'o' : { printf("po"); } break; } }
putchar('\n');
return 0; } |
C | #include <stdio.h>
#include <conio.h>
#include <math.h>
int main()
{
int n, sum;
printf("n = ");
scanf("%d",&n);
while (n>0)
{
sum+=n%10;
n=n/10;
}
printf("sum = %d", sum);
return 0;
} |
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* workshop.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ofrost-g <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/05/31 12:48:08 by ofrost-g #+# #+# */
/* Updated: 2019/06/07 12:04:36 by ofrost-g ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/fractol.h"
int phoenix(int x, int y, t_fractol *f)
{
int i;
double x_temp;
double y_temp;
double x_old;
double y_old;
i = 0;
x_old = 1;
y_old = 0;
f->p.y = f->w / f->h * (x - f->w / 2) / (0.5 * f->img.zoom * f->w)
- f->img.step_x;
f->p.x = (y - f->h / 2) / (0.5 * f->img.zoom * f->h) + f->img.step_y;
while (f->p.x * f->p.x + f->p.y * f->p.y < 4 && i < f->max_iter)
{
y_temp = 2 * f->p.x * f->p.y - f->img.c_im * y_old;
x_temp = f->p.x * f->p.x - f->p.y * f->p.y - f->img.c_re
- f->img.c_re * x_old;
x_old = f->p.x;
y_old = f->p.y;
f->p.x = x_temp;
f->p.y = y_temp;
i++;
}
return (i);
}
int dragon(int x, int y, t_fractol *f)
{
int i;
double y_temp;
double sq;
double prod;
i = 0;
f->p.x = f->w / f->h * (x - f->w / 4) / (f->img.zoom * f->w)
- f->img.step_x;
f->p.y = (y - f->h / 2) / (f->img.zoom * f->h) + f->img.step_y;
f->img.c_re = 1.646;
f->img.c_im = 0.967;
while (f->p.x * f->p.x + f->p.y * f->p.y <= 4 && i < 256)
{
sq = f->p.y * f->p.y - f->p.x * f->p.x;
prod = 2 * f->p.x * f->p.y;
y_temp = f->img.c_im * (sq + f->p.x) - f->img.c_re * (prod - f->p.y);
f->p.x = f->img.c_re * (sq + f->p.x) + f->img.c_im * (prod - f->p.y);
f->p.y = y_temp;
i++;
}
if (i >= 256)
return ((int)((f->p.x * f->p.x + f->p.y * f->p.y) * 8)) % 7 + 9;
else
return (1);
}
int julia(int x, int y, t_fractol *f)
{
int i;
double c_re;
double c_im;
double x_temp;
double y_temp;
i = 0;
f->p.x = f->w / f->h * (x - f->w / 2) / (f->img.zoom * f->w / 2)
- f->img.step_x;
f->p.y = (y - f->h / 2) / (f->img.zoom * f->h / 2) + f->img.step_y;
c_re = f->img.c_re;
c_im = f->img.c_im;
while (f->p.x * f->p.x + f->p.y * f->p.y <= 4 && i < f->max_iter)
{
x_temp = f->p.x * f->p.x - f->p.y * f->p.y + c_re;
y_temp = 2 * f->p.x * f->p.y + c_im;
f->p.x = x_temp;
f->p.y = y_temp;
i++;
}
return (i);
}
double mandelbrot(int x, int y, t_fractol *f)
{
int i;
double xin;
double yin;
double x_temp;
i = 0;
xin = 0;
yin = 0;
f->img.c_re = (x - f->w / 2.0) * 3.0 * f->img.zoom / f->w - f->img.step_x;
f->img.c_im = (y - f->h / 2.0) * 3.0 * f->img.zoom / f->w + f->img.step_y;
while (xin * xin + yin * yin <= 4 && i < f->max_iter)
{
x_temp = xin * xin - yin * yin + f->img.c_re - 0.5;
yin = 2 * xin * yin + f->img.c_im;
xin = x_temp;
i++;
}
return (i);
}
void set_fractal_step_one(t_fractol *f)
{
f->type = 1;
f->img.step_x = 0;
f->img.step_y = 0;
f->img.color1 = 0;
f->img.color2 = 35;
f->img.zoom = 1;
f->img.c_re = -0.66000;
f->img.c_im = -0.40000;
f->max_iter = MAX_ITER;
f->h = HEIGHT;
f->w = WIDTH;
f->thr_num = 4;
f->p.x = 0;
f->p.y = 0;
f->s = f->h / 5;
}
|
C | /*! @file
@brief
mruby/c Fixnum and Float class
<pre>
Copyright (C) 2015-2018 Kyushu Institute of Technology.
Copyright (C) 2015-2018 Shimane IT Open-Innovation Center.
This file is distributed under BSD 3-Clause License.
</pre>
*/
#include "vm_config.h"
#include "opcode.h"
#include <stdio.h>
#include <limits.h>
#if MRBC_USE_FLOAT
#include <math.h>
#endif
#include "value.h"
#include "class.h"
#include "console.h"
#include "c_numeric.h"
#include "c_string.h"
//================================================================
/*! (operator) [] bit reference
*/
static void c_fixnum_bitref(struct VM *vm, mrbc_value v[], int argc)
{
if( mrbc_fixnum(v[1]) < 0 ) {
SET_INT_RETURN( 0 );
} else {
mrbc_int mask = (argc == 1) ? 1 : (1 << mrbc_fixnum(v[2])) - 1;
SET_INT_RETURN( (mrbc_fixnum(v[0]) >> mrbc_fixnum(v[1])) & mask );
}
}
//================================================================
/*! (operator) unary +
*/
static void c_fixnum_positive(struct VM *vm, mrbc_value v[], int argc)
{
// do nothing
}
//================================================================
/*! (operator) unary -
*/
static void c_fixnum_negative(struct VM *vm, mrbc_value v[], int argc)
{
mrbc_int num = GET_INT_ARG(0);
SET_INT_RETURN( -num );
}
//================================================================
/*! (operator) ** power
*/
static void c_fixnum_power(struct VM *vm, mrbc_value v[], int argc)
{
if( v[1].tt == MRBC_TT_FIXNUM ) {
mrbc_int x = 1;
int i;
if( v[1].i < 0 ) x = 0;
for( i = 0; i < v[1].i; i++ ) {
x *= v[0].i;;
}
SET_INT_RETURN( x );
}
#if MRBC_USE_FLOAT && MRBC_USE_MATH
else if( v[1].tt == MRBC_TT_FLOAT ) {
SET_FLOAT_RETURN( pow( v[0].i, v[1].d ) );
}
#endif
}
//================================================================
/*! (operator) %
*/
static void c_fixnum_mod(struct VM *vm, mrbc_value v[], int argc)
{
mrbc_int num = GET_INT_ARG(1);
SET_INT_RETURN( v->i % num );
}
//================================================================
/*! (operator) &; bit operation AND
*/
static void c_fixnum_and(struct VM *vm, mrbc_value v[], int argc)
{
mrbc_int num = GET_INT_ARG(1);
SET_INT_RETURN(v->i & num);
}
//================================================================
/*! (operator) |; bit operation OR
*/
static void c_fixnum_or(struct VM *vm, mrbc_value v[], int argc)
{
mrbc_int num = GET_INT_ARG(1);
SET_INT_RETURN(v->i | num);
}
//================================================================
/*! (operator) ^; bit operation XOR
*/
static void c_fixnum_xor(struct VM *vm, mrbc_value v[], int argc)
{
mrbc_int num = GET_INT_ARG(1);
SET_INT_RETURN( v->i ^ num );
}
//================================================================
/*! (operator) ~; bit operation NOT
*/
static void c_fixnum_not(struct VM *vm, mrbc_value v[], int argc)
{
mrbc_int num = GET_INT_ARG(0);
SET_INT_RETURN( ~num );
}
//================================================================
/*! x-bit left shift for x
*/
static mrbc_int shift(mrbc_int x, mrbc_int y)
{
// Don't support environments that include padding in int.
const int INT_BITS = sizeof(mrbc_int) * CHAR_BIT;
if( y >= INT_BITS ) return 0;
if( y >= 0 ) return x << y;
if( y <= -INT_BITS ) return 0;
return x >> -y;
}
//================================================================
/*! (operator) <<; bit operation LEFT_SHIFT
*/
static void c_fixnum_lshift(struct VM *vm, mrbc_value v[], int argc)
{
int num = GET_INT_ARG(1);
SET_INT_RETURN( shift(v->i, num) );
}
//================================================================
/*! (operator) >>; bit operation RIGHT_SHIFT
*/
static void c_fixnum_rshift(struct VM *vm, mrbc_value v[], int argc)
{
int num = GET_INT_ARG(1);
SET_INT_RETURN( shift(v->i, -num) );
}
//================================================================
/*! (method) abs
*/
static void c_fixnum_abs(struct VM *vm, mrbc_value v[], int argc)
{
if( v[0].i < 0 ) {
v[0].i = -v[0].i;
}
}
#if MRBC_USE_FLOAT
//================================================================
/*! (method) to_f
*/
static void c_fixnum_to_f(struct VM *vm, mrbc_value v[], int argc)
{
mrbc_float f = GET_INT_ARG(0);
SET_FLOAT_RETURN( f );
}
#endif
#if MRBC_USE_STRING
//================================================================
/*! (method) chr
*/
static void c_fixnum_chr(struct VM *vm, mrbc_value v[], int argc)
{
char buf[2] = { GET_INT_ARG(0) };
mrbc_value value = mrbc_string_new(vm, buf, 1);
SET_RETURN(value);
}
//================================================================
/*! (method) to_s
*/
static void c_fixnum_to_s(struct VM *vm, mrbc_value v[], int argc)
{
int base = 10;
if( argc ) {
base = GET_INT_ARG(1);
if( base < 2 || base > 36 ) {
return; // raise ? ArgumentError
}
}
mrbc_printf pf;
char buf[16];
mrbc_printf_init( &pf, buf, sizeof(buf), NULL );
pf.fmt.type = 'd';
mrbc_printf_int( &pf, v->i, base );
mrbc_printf_end( &pf );
mrbc_value value = mrbc_string_new_cstr(vm, buf);
SET_RETURN(value);
}
#endif
/* MRBC_AUTOGEN_METHOD_TABLE
CLASS("Fixnum")
FILE("method_table_fixnum.h")
FUNC("mrbc_init_class_fixnum")
METHOD( "[]", c_fixnum_bitref )
METHOD( "+@", c_fixnum_positive )
METHOD( "-@", c_fixnum_negative )
METHOD( "**", c_fixnum_power )
METHOD( "%", c_fixnum_mod )
METHOD( "&", c_fixnum_and )
METHOD( "|", c_fixnum_or )
METHOD( "^", c_fixnum_xor )
METHOD( "~", c_fixnum_not )
METHOD( "<<", c_fixnum_lshift )
METHOD( ">>", c_fixnum_rshift )
METHOD( "abs", c_fixnum_abs )
METHOD( "to_i", c_ineffect )
#if MRBC_USE_FLOAT
METHOD( "to_f", c_fixnum_to_f )
#endif
#if MRBC_USE_STRING
METHOD( "chr", c_fixnum_chr )
METHOD( "inspect", c_fixnum_to_s )
METHOD( "to_s", c_fixnum_to_s )
#endif
*/
#include "method_table_fixnum.h"
// Float
#if MRBC_USE_FLOAT
//================================================================
/*! (operator) unary +
*/
static void c_float_positive(struct VM *vm, mrbc_value v[], int argc)
{
// do nothing
}
//================================================================
/*! (operator) unary -
*/
static void c_float_negative(struct VM *vm, mrbc_value v[], int argc)
{
mrbc_float num = GET_FLOAT_ARG(0);
SET_FLOAT_RETURN( -num );
}
#if MRBC_USE_MATH
//================================================================
/*! (operator) ** power
*/
static void c_float_power(struct VM *vm, mrbc_value v[], int argc)
{
mrbc_float n = 0;
switch( v[1].tt ) {
case MRBC_TT_FIXNUM: n = v[1].i; break;
case MRBC_TT_FLOAT: n = v[1].d; break;
default: break;
}
SET_FLOAT_RETURN( pow( v[0].d, n ));
}
#endif
//================================================================
/*! (method) abs
*/
static void c_float_abs(struct VM *vm, mrbc_value v[], int argc)
{
if( v[0].d < 0 ) {
v[0].d = -v[0].d;
}
}
//================================================================
/*! (method) to_i
*/
static void c_float_to_i(struct VM *vm, mrbc_value v[], int argc)
{
mrbc_int i = (mrbc_int)GET_FLOAT_ARG(0);
SET_INT_RETURN( i );
}
#if MRBC_USE_STRING
//================================================================
/*! (method) to_s
*/
static void c_float_to_s(struct VM *vm, mrbc_value v[], int argc)
{
char buf[16];
snprintf( buf, sizeof(buf), "%g", v->d );
mrbc_value value = mrbc_string_new_cstr(vm, buf);
SET_RETURN(value);
}
#endif
/* MRBC_AUTOGEN_METHOD_TABLE
CLASS("Float")
FILE("method_table_float.h")
FUNC("mrbc_init_class_float")
METHOD( "+@", c_float_positive )
METHOD( "-@", c_float_negative )
#if MRBC_USE_MATH
METHOD( "**", c_float_power )
#endif
METHOD( "abs", c_float_abs )
METHOD( "to_i", c_float_to_i )
METHOD( "to_f", c_ineffect )
#if MRBC_USE_STRING
METHOD( "inspect", c_float_to_s )
METHOD( "to_s", c_float_to_s )
#endif
*/
#include "method_table_float.h"
#endif // MRBC_USE_FLOAT
|
C | //Lucas Eduardo Nogueira Gonalves, 122055 (Integral)
#include <stdio.h>
#include <stdlib.h>
void Imprimevetor(int n, int *vet) /* funo de impresso */
{
int i;
for (i = 0; i < n; i++)
printf("%d ", vet[i]);
printf("\n"); /* pula uma linha */
}
int EncontraMaior(int n, int *vet) /* funo que encontra o maior elemento */
{
int i, maior, aux;
maior = vet[0]; /* primeira posio do vetor */
for (i = 1; i < n; i++) /* percorre todo o vetor */
if (vet[i] > maior)
maior = vet[i]; /* troca quando encontrar o maior elemento */
return maior;
}
int *InicializaContador(int maior) /* funo que inicializa o contador com 0 */
{
int i, *vetcont;
vetcont = (int *)malloc(sizeof(int) * (maior + 1)); /* vai de 0 at o maior elemento */
for (i = 0; i < maior + 1; i++)
vetcont[i] = 0; /* a contagem inicia no zero */
return vetcont;
}
void CountingSort(int n, int *vet, int *vetaux, int exp) /* countingsort modificado */
{
int i, maior, *vetcont, *vetdivid;
vetdivid = (int *)malloc(sizeof(int) * n); /* vetor que ira armazernar cada digito (unidade, dezena, centena, ...) */
for (i = 0; i < n; i++)
vetdivid[i] = (vet[i] / exp) % 10; /* armazena tal posio */
maior = EncontraMaior(n, vetdivid); /* encontra o maior elemento (note que o max 9) */
vetcont = InicializaContador(maior); /* inicia o novo contador com 0 */
for (i = 0; i < n; i++)
vetcont[vetdivid[i]] += 1; /* verifica onde cada um inicia */
for (i = 1; i <= maior; i++)
vetcont[i] += vetcont[i - 1]; /* soma acumulada */
for (i = n - 1; i >= 0; i--)
{
vetcont[vetdivid[i]]--; /* o contador na posio do elemento decresce */
vetaux[vetcont[vetdivid[i]]] = vet[i]; /* ordena (vetaux vai carregar o vetor ordenado) */
}
for (i = 0; i < n; i++)
vet[i] = vetaux[i]; /* como vamos precisar do vet novamente, atualizamos as novas posies */
free(vetdivid); /* libera os dois vetores alocados na funo */
free(vetcont);
}
int EncontraDigito(int n, int *vet) /* encontra a quantidade de digitos do maior elemento */
{
int i, d, maior;
i = 1;
d = 1;
maior = EncontraMaior(n, vet); /* pega o maior elemento do vetor */
while (maior / i != 0) /* enquanto a diviso por potencias de 10 no for zero vamos somando 1 no contador*/
{
i *= 10;
d++;
}
return d; /* retorna quantas vezes dividimos por 10 e equivalente ao numero de digitos */
}
void RadixSort(int d, int n, int *vet, int *vetaux) /* RadixSort */
{
int i, exp;
exp = 1; /* sera equivalente as potencias de 10 */
for (i = 1; i < d; i++) /* ordenamos at o numero de digitos */
{
CountingSort(n, vet, vetaux, exp); /* ordenao por counting */
exp *= 10; /* atualiza a potencia */
Imprimevetor(n, vetaux); /* imprime o vetor "ordenado" */
}
}
int main()
{
int i, n, d, maior, *vet, *vetaux;
scanf("%d", &n); /* leitura do tamanho */
vet = (int *)malloc(sizeof(int) * n); /* alocaco do vetor principal */
vetaux = (int *)malloc(sizeof(int) * n); /* alocao do auxiliar */
for (i = 0; i < n; i++)
scanf("%d", &vet[i]); /* leitura dos elementos */
d = EncontraDigito(n, vet); /* encontra o numero de digitos */
RadixSort(d, n, vet, vetaux); /* ordenao por radix */
free(vetaux); /* libera os vetores */
free(vet);
return 0;
}
|
C | #include <string.h>
#include <stdlib.h>
#include "dberror.h"
#include "expr.h"
#include "tables.h"
// implementations
RC
valueEquals (Value *left, Value *right, Value *result)
{
if(left->dt != right->dt)
THROW(RC_RM_COMPARE_VALUE_OF_DIFFERENT_DATATYPE, "equality comparison only supported for values of the same datatype");
result->dt = DT_BOOL;
switch(left->dt) {
case DT_INT:
result->v.boolV = (left->v.intV == right->v.intV);
break;
case DT_FLOAT:
result->v.boolV = (left->v.floatV == right->v.floatV);
break;
case DT_BOOL:
result->v.boolV = (left->v.boolV == right->v.boolV);
break;
case DT_STRING:
result->v.boolV = (strcmp(left->v.stringV, right->v.stringV) == 0);
break;
}
return RC_OK;
}
RC
valueSmaller (Value *left, Value *right, Value *result)
{
if(left->dt != right->dt)
THROW(RC_RM_COMPARE_VALUE_OF_DIFFERENT_DATATYPE, "equality comparison only supported for values of the same datatype");
result->dt = DT_BOOL;
switch(left->dt) {
case DT_INT:
result->v.boolV = (left->v.intV < right->v.intV);
break;
case DT_FLOAT:
result->v.boolV = (left->v.floatV < right->v.floatV);
break;
case DT_BOOL:
result->v.boolV = (left->v.boolV < right->v.boolV);
case DT_STRING:
result->v.boolV = (strcmp(left->v.stringV, right->v.stringV) < 0);
break;
}
return RC_OK;
}
RC
boolNot (Value *input, Value *result)
{
if (input->dt != DT_BOOL)
THROW(RC_RM_BOOLEAN_EXPR_ARG_IS_NOT_BOOLEAN, "boolean NOT requires boolean input");
result->dt = DT_BOOL;
result->v.boolV = !(input->v.boolV);
return RC_OK;
}
RC
boolAnd (Value *left, Value *right, Value *result)
{
if (left->dt != DT_BOOL || right->dt != DT_BOOL)
THROW(RC_RM_BOOLEAN_EXPR_ARG_IS_NOT_BOOLEAN, "boolean AND requires boolean inputs");
result->v.boolV = (left->v.boolV && right->v.boolV);
return RC_OK;
}
RC
boolOr (Value *left, Value *right, Value *result)
{
if (left->dt != DT_BOOL || right->dt != DT_BOOL)
THROW(RC_RM_BOOLEAN_EXPR_ARG_IS_NOT_BOOLEAN, "boolean OR requires boolean inputs");
result->v.boolV = (left->v.boolV || right->v.boolV);
return RC_OK;
}
RC
evalExpr (Record *record, Schema *schema, Expr *expr, Value **result)
{
Value *lIn;
Value *rIn;
MAKE_VALUE(*result, DT_INT, -1);
switch(expr->type)
{
case EXPR_OP:
{
Operator *op = expr->expr.op;
bool twoArgs = (op->type != OP_BOOL_NOT);
// lIn = (Value *) malloc(sizeof(Value));
// rIn = (Value *) malloc(sizeof(Value));
CHECK(evalExpr(record, schema, op->args[0], &lIn));
if (twoArgs)
CHECK(evalExpr(record, schema, op->args[1], &rIn));
switch(op->type)
{
case OP_BOOL_NOT:
CHECK(boolNot(lIn, *result));
break;
case OP_BOOL_AND:
CHECK(boolAnd(lIn, rIn, *result));
break;
case OP_BOOL_OR:
CHECK(boolOr(lIn, rIn, *result));
break;
case OP_COMP_EQUAL:
CHECK(valueEquals(lIn, rIn, *result));
break;
case OP_COMP_SMALLER:
CHECK(valueSmaller(lIn, rIn, *result));
break;
default:
break;
}
// cleanup
freeVal(lIn);
if (twoArgs)
freeVal(rIn);
}
break;
case EXPR_CONST:
CPVAL(*result,expr->expr.cons);
break;
case EXPR_ATTRREF:
free(*result);
CHECK(getAttrs(record, schema, expr->expr.attrRef, result));
break;
}
return RC_OK;
}
RC
freeExpr (Expr *expr)
{
switch(expr->type)
{
case EXPR_OP:
{
Operator *op = expr->expr.op;
switch(op->type)
{
case OP_BOOL_NOT:
freeExpr(op->args[0]);
break;
default:
freeExpr(op->args[0]);
freeExpr(op->args[1]);
break;
}
free(op->args);
free(op);
}
break;
case EXPR_CONST:
freeVal(expr->expr.cons);
break;
case EXPR_ATTRREF:
break;
}
free(expr);
return RC_OK;
}
void
freeVal (Value *val)
{
if (val->dt == DT_STRING)
free(val->v.stringV);
free(val);
}
RC getAttrs (Record *record, Schema *schema, int attrNum, Value **value)
{
int offset;
char *attrData;
attrOffsets(schema, attrNum, &offset);
attrData = record->data + offset;
switch(schema->dataTypes[attrNum])
{
case DT_INT:
{
int val = 0;
val = atoi(attrData);
MAKE_VALUE(*value, DT_INT, val);
}
break;
case DT_STRING:
{
char *buf;
int len = schema->typeLength[attrNum];
buf = (char *) malloc(len + 1);
strncpy(buf, attrData, len);
buf[len] = '\0';
MAKE_STRING_VALUE(*value, buf);
free(buf);
}
break;
case DT_FLOAT:
{
float val;
val = atof(attrData);
MAKE_VALUE(*value, DT_FLOAT, val);
}
break;
case DT_BOOL:
{
bool val;
memcpy(&val,attrData, sizeof(bool));
MAKE_VALUE(*value, DT_BOOL, val);
}
break;
}
return RC_OK;
}
RC
attrOffsets (Schema *schema, int attrNum, int *result)
{
int offset = 0;
int attrPos = 0;
for(attrPos = 0; attrPos < attrNum; attrPos++)
switch (schema->dataTypes[attrPos])
{
case DT_STRING:
offset += schema->typeLength[attrPos];
break;
case DT_INT:
offset += sizeof(int);
break;
case DT_FLOAT:
offset += sizeof(float);
break;
case DT_BOOL:
offset += sizeof(bool);
break;
}
*result = offset;
return RC_OK;
}
Value *
stringToValue(char *val)
{
Value *result = (Value *) malloc(sizeof(Value));
switch(val[0])
{
case 'i':
result->dt = DT_INT;
result->v.intV = atoi(val + 1);
break;
case 'f':
result->dt = DT_FLOAT;
result->v.floatV = atof(val + 1);
break;
case 's':
result->dt = DT_STRING;
result->v.stringV = malloc(strlen(val));
strcpy(result->v.stringV, val + 1);
break;
case 'b':
result->dt = DT_BOOL;
result->v.boolV = (val[1] == 't') ? TRUE : FALSE;
break;
default:
result->dt = DT_INT;
result->v.intV = -1;
break;
}
return result;
}
|
C | #include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <stdio.h>
#include <list.h>
#include "animate.h"
#include "dbg.h"
#include "flags.h"
#include "sprite.h"
#include "gfx.h"
Sprite *create_sprite(char *id, char *path, int frames, SDL_Rect *size, SDL_Rect *mask, void *animation)
{
Sprite *sprite = malloc(sizeof(Sprite));
sprite->animations = NULL;
sprite->animation = animation;
sprite->alpha = ALPHA_MAX;
sprite->flags = 0;
sprite->frames = frames;
sprite->id = id;
sprite->is_animating = 0;
sprite->mask = mask;
sprite->path = path;
sprite->size = size;
sprite->texture = create_sprite_texture(renderer, path, ALPHA_MAX);
sprite->visible = 1;
return sprite;
}
void add_animation(Sprite *sprite, Animation2 *animation)
{
List_push(&sprite->animations, animation);
}
SDL_Texture *create_sprite_texture(SDL_Renderer *renderer, char *imgPath, int alpha)
{
SDL_Surface *sprite_surface = IMG_Load(imgPath);
check(sprite_surface, "Could not load image: %s, error = %s", imgPath, SDL_GetError())
SDL_Texture *sprite_texture = SDL_CreateTextureFromSurface(renderer, sprite_surface);
check(sprite_texture, "Could not create texture: %s", SDL_GetError());
SDL_SetTextureAlphaMod(sprite_texture, alpha);
SDL_FreeSurface(sprite_surface);
return sprite_texture;
error:
SDL_Quit();
log_err("SDL Error: Shutdown");
return NULL;
}
Node *cleanup_sprite(Sprite *sprite, Node **render_index, int node_id)
{
Node *updated_node;
// Clean up the sprite
if(sprite->flags & FLAG_REMOVE) {
// Remove the flag
sprite->flags &= ~(FLAG_REMOVE);
// Destroy the sprite
destroy_sprite(sprite);
// Remove the node and get the next node
updated_node = List_remove(render_index, node_id);
return updated_node;
}
return NULL;
}
void destroy_sprite(Sprite *sprite)
{
/*debug("destroy sprite");*/
if(sprite->id) {
free(sprite->id);
}
if(sprite->size) {
free(sprite->size);
}
if(sprite->mask) {
free(sprite->mask);
}
if(sprite->animation) {
free(sprite->animation);
Animation *animation = (Animation *)sprite->animation;
if(animation->type == BEZIER) {
/*debug("bezier");*/
}
}
free(sprite);
}
|
C | /* version where reders can read all items in a row
/* they dont wait for consumer */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/shm.h>
#include <time.h>
#include <errno.h>
#include <sys/types.h>
#include <signal.h>
#include <semaphore.h>
#include <pthread.h>
#define BUFFER_SIZE 5
#define NITERS 2000
#define NREADERS 3
#define RED "\x1B[31m"
#define GREEN "\x1B[32m"
#define YELLOW "\x1B[33m"
#define RESET "\x1B[0m"
#define READER_SLEEP 2
#define CONSUMER_SLEEP 5
#define PRODUCER_SLEEP 1
typedef struct
{
int buf[BUFFER_SIZE];
int in;//index of first empty slot
int out;//index of last slot
int rindex[NREADERS];//where reders are
int nreads[BUFFER_SIZE];//how much each element have been read
sem_t empty;//free places
sem_t full;//non-free places
sem_t mutex;//critical section
sem_t readers[NREADERS];
sem_t cons; // how much elements have readen
//sem_t consreader; // communication between consumer and reader
}Buffer;
Buffer shared;
void print_buffer()
{
int i;
for(i = 0;i<BUFFER_SIZE;i++)
{
if(shared.buf[i] == 0) printf("_");
else if (shared.nreads[i]==0) printf("%d",shared.buf[i]);
else if (shared.nreads[i]==1) printf(GREEN "%d",shared.buf[i]);
else if (shared.nreads[i]==2) printf(YELLOW "%d",shared.buf[i]);
else if (shared.nreads[i]==3) printf(RED "%d",shared.buf[i]);
printf(RESET);
}
printf("\n");
}
void print_semaphors()
{
int e,f,r1,r2,r3,c;
sem_getvalue(&shared.empty,&e);
sem_getvalue(&shared.full,&f);
sem_getvalue(&shared.readers[0],&r1);
sem_getvalue(&shared.readers[1],&r2);
sem_getvalue(&shared.readers[2],&r3);
sem_getvalue(&shared.cons,&c);
printf("E|%d F|%d R1|%d R2|%d R3|%d C|%d ",e,f,r1,r2,r3,c);
}
void random_sleep(int i)
{
int x;
x = (rand()%i)+1;
sleep(x);
}
void *Producer()
{
int item,i;
for(i = 0 ; i<NITERS ; i++ )
{
item = (rand() % 9) + 1;
//printf("p");
sem_wait(&shared.empty); // dec empty
sem_wait(&shared.mutex); // dec critical section
shared.buf[shared.in] = item;
shared.in = (shared.in+1)%BUFFER_SIZE;//inc in index
sem_post(&shared.full);
sem_post(&shared.readers[0]);
sem_post(&shared.readers[1]);
sem_post(&shared.readers[2]);
print_semaphors();
printf("[P] producing %d ", item);
print_buffer();
sem_post(&shared.mutex);
random_sleep(PRODUCER_SLEEP);
}
}
void *Consumer()
{
int item,i,j,error,prev;
for(i = 0 ; i<NITERS ; i++ )
{
//printf("c");
sem_wait(&shared.cons); // wait for readers will read
sem_wait(&shared.full);//wait for producer
sem_wait(&shared.mutex);
print_semaphors();
item = shared.buf[shared.out]; // get object
shared.buf[shared.out] = 0; //erase object
if(shared.nreads[shared.out] < NREADERS ||
shared.nreads[shared.out] == 4 || // for special read (when double read occurs)
shared.nreads[shared.out] == 5 ||
shared.nreads[shared.out] == 6 )
{//if two readers dont need to read this yet means that one read this
//so we need to run up readers
for(j = 0; j<NREADERS ; j++)
{//search for this reader
if(shared.rindex[j] == shared.out)
{
shared.rindex[j]=(shared.rindex[j]+1)%BUFFER_SIZE;
}
}
}
printf("[C] consume %d ", item);
print_buffer();
shared.nreads[shared.out] = 0;
sem_post(&shared.mutex);
sem_post(&shared.empty);
prev = shared.nreads[shared.out];
shared.out = (shared.out+1)%BUFFER_SIZE; // inc index of new slot
if(prev == 1 || shared.buf[shared.out] == 0)
{//consumer sleeps only if element that it consume have been readen once
random_sleep(CONSUMER_SLEEP);
}else
{//double read
if(prev == 2 || prev == 3 || prev == 6 || prev == 7)
{
if(shared.nreads[shared.out] == 0)
{
shared.nreads[shared.out] = 4 ; //special nreads
sem_post(&shared.cons);
}
}
}
}//for
printf("Consumer finished!\n");
}
void *Reader(void *arg)
{
int i,index,check;
index = (int)arg; // reader index
for(i = 0 ; i<NITERS ; i++ )
{
//printf("r");
sem_wait(&shared.readers[index]); // wait until it can read
sem_wait(&shared.mutex);
check = 1;// to limit reader
if(shared.in >= shared.out){
if( shared.rindex[index] >= shared.in || shared.rindex[index] < shared.out ){check = 0;}
//else if(shared.rindex[index] < shared.out){check = 0;}
}else {
if(shared.rindex[index] >= shared.in && shared.rindex[index] < shared.out){check = 0;}
}
if(shared.nreads[shared.rindex[index]]>=2) check = 0;//reader cant read more then two times
if(check == 1)
{
shared.nreads[shared.rindex[index]]++;
if(shared.nreads[shared.rindex[index]] == 1)
sem_post(&shared.cons);//cons can cons item
print_semaphors();
printf("[R%d] reading %d ", index+1,shared.buf[shared.rindex[index]]);
print_buffer();
shared.rindex[index]=(shared.rindex[index]+1)%BUFFER_SIZE;
}
sem_post(&shared.mutex);
if(check == 1)
random_sleep(READER_SLEEP);
}
printf("Reader finished!\n");
}
int main()
{
pthread_t idP, idC, idR1,idR2,idR3;
sem_init(&shared.full, 0, 0);
sem_init(&shared.empty, 0, BUFFER_SIZE);
sem_init(&shared.mutex, 0, 1);
sem_init(&shared.readers[0],0 , 0);
sem_init(&shared.readers[1],0 , 0);
sem_init(&shared.readers[2],0 , 0);
sem_init(&shared.cons,0,0);
pthread_create(&idP, NULL, Producer, NULL);
pthread_create(&idC, NULL, Consumer, NULL);
pthread_create(&idR1, NULL, Reader, (void*)0);
pthread_create(&idR2, NULL, Reader, (void*)1);
pthread_create(&idR3, NULL, Reader, (void*)2);
pthread_exit(NULL);
return 0;
}
|
C | #define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_7__ TYPE_2__ ;
typedef struct TYPE_6__ TYPE_1__ ;
/* Type definitions */
struct TYPE_7__ {int x; int y; int z; int face; } ;
struct TYPE_6__ {int size; TYPE_2__* data; } ;
typedef TYPE_1__ SignList ;
typedef TYPE_2__ Sign ;
/* Variables and functions */
int /*<<< orphan*/ memcpy (TYPE_2__*,TYPE_2__*,int) ;
int sign_list_remove(SignList *list, int x, int y, int z, int face) {
int result = 0;
for (int i = 0; i < list->size; i++) {
Sign *e = list->data + i;
if (e->x == x && e->y == y && e->z == z && e->face == face) {
Sign *other = list->data + (--list->size);
memcpy(e, other, sizeof(Sign));
i--;
result++;
}
}
return result;
} |
C | /* Parsing: Evaluating Arithmetic Expressions
=================================================================
Description: Given a infix expression in a string, the parser
evaluates the string and reports errors if the
parsing fails or the evaluation causes a division by
zero.
Complexity: O(N) where N is the size of the string
-----------------------------------------------------------------
Author: Patrick Earl
Date: Nov 14, 2002
-----------------------------------------------------------------
Reliability: 0
Notes: Leading zeros are handled.
By default, the code uses long long, but it cannot handle
the minimum long long value, only that value plus one.
Overflow in the math operations is not checked.
Whitespace is ignored.
Expressions follow this grammar:
Expr = Term (('+'|'-') Term) *
Term = Factor (('*'|'/') Factor) *
Factor = Unit | ('+'|'-')? Factor
Unit = LongLongInteger | '('Expr')'
*/
#include <stdio.h>
#include <ctype.h>
#include <limits.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
enum {
SUCCESS,
DIV_BY_ZERO, /* A division by zero would have occured. */
PARSE_UNEXPECTED,/* Unexpected character. Also reported for empty
string. */
PARSE_TOOLONG, /* Extra non-whitespace junk after complete
expression has been parsed. */
PARSE_OVERFLOW, /* Integer is too long to fit in an int. */
PARSE_NOPAREN /* No matching parentheses. */
};
/* If you change this, you need to change the low level parsing as well. */
typedef long long TYPE;
char *s;
int pos;
int error;
char gc() {
while(isspace(s[pos])) pos++;
return s[pos++];
}
void ugc() {
pos--;
}
TYPE Expr();
TYPE Unit() {
char c;
TYPE expr;
char num[100];
char *ref;
int p, zero;
c = gc();
if(c == '(') {
expr = Expr();
if(error) return 0;
if(gc() != ')') {
error = PARSE_NOPAREN;
return 0;
}
return expr;
} else if(isdigit(c)) {
p=0;
zero=1;
while(isdigit(c)) {
if(zero && c=='0') {
c=gc();
continue;
}
zero=0;
num[p++]=c;
if(p > 19) {
error = PARSE_OVERFLOW;
return 0;
}
c=gc();
}
ugc();
if(zero) num[p++]='0';
num[p]=0;
/* The largest 64 bit long long value. */
ref = "9223372036854775807";
if(strlen(num) == strlen(ref) && strcmp(num, ref) > 0) {
error = PARSE_OVERFLOW;
return 0;
}
if(sscanf(num,"%lld",&expr) != 1) {
error = PARSE_OVERFLOW;
return 0;
}
return expr;
} else {
error=PARSE_UNEXPECTED;
return 0;
}
}
TYPE Factor() {
char c = gc();
/* Unary +/- is handled here. */
if(c == '-') {
return -Factor();
} else if(c == '+') {
return Factor();
} else {
ugc();
return Unit();
}
}
TYPE Term() {
TYPE total;
TYPE factor;
char c;
total = Factor();
if(error) return 0;
while(1) {
c = gc();
if(c == '*') {
total *= Factor();
if(error) return 0;
} else if(c == '/') {
factor = Factor();
if(error) return 0;
if(factor == 0) {
error = DIV_BY_ZERO;
return 0;
}
total /= factor;
} else {
ugc();
return total;
}
}
}
TYPE Expr() {
TYPE total;
char c;
total = Term();
if(error) return 0;
while(1) {
c = gc();
if(c == '-') {
total -= Term();
if(error) return 0;
} else if(c == '+') {
total += Term();
if(error) return 0;
} else {
ugc();
return total;
}
}
}
TYPE parse(char *str) {
TYPE res;
s = str;
error = SUCCESS;
pos = 0;
res = Expr();
if(!error && gc() != 0) error=PARSE_TOOLONG;
return res;
}
void chomp(char *s) {
int len = strlen(s);
if(s[len-1]=='\n') s[len-1]=0;
}
int main() {
char line[1000];
TYPE res;
while(fgets(line,1000,stdin)) {
res=parse(line);
chomp(line);
printf("Parsed: %s\n",line);
switch(error) {
case SUCCESS:
printf("The value of the expression is: %lld\n",res);
break;
case DIV_BY_ZERO:
printf("A division by zero occured.\n");
break;
case PARSE_UNEXPECTED:
printf("An unexpected character was encountered.\n");
break;
case PARSE_TOOLONG:
printf("There was extra junk at the end of the string.\n");
break;
case PARSE_OVERFLOW:
printf("An integer was parsed that would not fit in int.\n");
break;
case PARSE_NOPAREN:
printf("A closing parenthesis was not found.\n");
break;
}
}
return 0;
}
|
C | /* cx17-ap6.c */
#include "stdio.h"
#include "malloc.h"
#define CLASS(type)\
typedef struct type type; \
struct type
#define CTOR(type) \
void* type##New() \
{ \
struct type *t; \
t = (struct type *)malloc(sizeof(struct type));
#define FUNCTION_SETTING(f1, f2) t->f1 = f2;
#define END_CTOR return (void*)t; };
/* */
CLASS(Rectangle)
{
void (*init)(struct Rectangle*, double, double);
double (*cal_area)(struct Rectangle*);
double (*cal_perimeter)(struct Rectangle*);
double length;
double width;
};
double cal_area_imp(Rectangle* cthis)
{
return cthis->length * cthis->width;
}
double cal_perimeter_imp(Rectangle* cthis)
{
return (cthis->length + cthis->width) * 2;
}
void init_imp(Rectangle* cthis, double len, double wid)
{
cthis->length = len;
cthis->width = wid;
}
CTOR(Rectangle)
FUNCTION_SETTING(init, init_imp)
FUNCTION_SETTING(cal_area,cal_area_imp)
FUNCTION_SETTING(cal_perimeter,cal_perimeter_imp)
END_CTOR
/*------------------------------------------*/
int main()
{
Rectangle* pr; double v;
pr = (Rectangle*)RectangleNew();
pr->init(pr, 10.5, 20.5);
v = pr->cal_area(pr);
printf("area=%7.3f\n", v);
v = pr->cal_perimeter(pr);
printf("perimeter=%7.3f\n", v);
getchar();
return 0;
}
|
C | #include <stdio.h>
/**
* 两个读线程读取数据,一个写线程更新数据
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#define READ_THREAD 0
#define WRITE_THREAD 1
int g_data = 0;
pthread_rwlock_t g_rwlock;
void *func(void *pdata)
{
int data = (int)pdata;
while (1) {
if (READ_THREAD == data) {
pthread_rwlock_rdlock(&g_rwlock);
printf("-----%d------ %d\n", pthread_self(), g_data);
sleep(1);
pthread_rwlock_unlock(&g_rwlock);
sleep(1);
}
else {
pthread_rwlock_wrlock(&g_rwlock);
g_data++;
printf("add the g_data\n");
pthread_rwlock_unlock(&g_rwlock);
sleep(1);
}
}
return NULL;
}
int main(int argc, char **argv)
{
pthread_t t1, t2, t3;
pthread_rwlock_init(&g_rwlock, NULL);
pthread_create(&t1, NULL, func, (void *)READ_THREAD);
pthread_create(&t2, NULL, func, (void *)READ_THREAD);
pthread_create(&t3, NULL, func, (void *)WRITE_THREAD);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_join(t3, NULL);
pthread_rwlock_destroy(&g_rwlock);
return 0;
}
|
C | #include <stdio.h>
#include "math.h"
int main()
{
int v[20], i, j, maiorIndice;
int maiorDiferenca, auxiliar;
for(i=0;i<20;i++)
{
printf("Digite um valor para o vetor:\n");
scanf("%d",&v[i]);
}
for(i=0;i<20;i++)
{
printf("%d\n",v[i]);
}
maiorIndice = 0;
maiorDiferenca = sqrt(pow((v[0] - v[1]),2));
printf("%d\n",maiorDiferenca);
for(i=1;i<19;i++)
{
auxiliar = sqrt(pow((v[i] - v[i+1]),2));
if(auxiliar>maiorDiferenca)
{
maiorDiferenca = auxiliar;
maiorIndice = i;
}
}
j = maiorIndice+1;
printf("Os elementos esto na posio: %d e %d\n",maiorIndice, j);
printf("A diferena entre eles : %d\n",maiorDiferenca);
return 0;
}
|
C | #include <stdio.h>
int main(){
char c = 'g';
int i = 10;
long l = 1;
char *cp = &c;
int *ip = &i;
long *lp = &l;
printf("*cp (oct): %o\t*cp (hex): %x\n", cp, cp);
printf("*ip (oct): %o\t*ip (hex): %x\n", ip, ip);
printf("*lp (oct): %o\t*lp (hex): %x\n", lp, lp);
printf("The addresses are right after one another, with the exception of the different sizes of the variables/number of bytes they each have\n");
printf("i: %d\n", i);
*ip += 2;
printf("i: %d\n", i);
printf("========Everything up to this is up to and not including part 6========\n");
unsigned int u = 948329528;
int *upi = &u;
char *upc = &u;
printf("upi: %d\t upi points to: %u\n", upi, *upi);
printf("upc: %c\t upc points to: %u\n", upc, *upc);
printf("u (dec): %u\tu (hex): %x\n", u, u);
unsigned int u1 = *upc;
unsigned int u2 = *(upc + 1);
unsigned int u3 = *(upc + 2);
unsigned int u4 = *(upc + 3);
printf("u: %u\t%u\t%u\t%u\n", u1, u2, u3, u4);
*upc += 1;
*(upc + 1) += 1;
*(upc + 2) += 1;
*(upc + 3) += 1;
printf("u (dec): %u\tu (hex): %x\n", *upi, *upi);
u1 = *upc;
u2 = *(upc + 1);
u3 = *(upc + 2);
u4 = *(upc + 3);
printf("u: %u\t%u\t%u\t%u\n", u1, u2, u3, u4);
*upc += 16;
*(upc + 1) += 16;
*(upc + 2) += 16;
*(upc + 3) += 16;
printf("u (dec): %u\tu (hex): %x\n", *upi, *upi);
u1 = *upc;
u2 = *(upc + 1);
u3 = *(upc + 2);
u4 = *(upc + 3);
printf("u: %u\t%u\t%u\t%u\n", u1, u2, u3, u4);
return 0;
} |
C | /**
* @file port/mswin/gettime.h
* @copyright 2021 Andrew MacIsaac
* @remark
* SPDX-License-Identifier: BSD-2-Clause
*
* @brief Port implementation to obtain time on Windows platforms.
*/
#ifndef PORT_MSWIN_GETTIME_H_
#define PORT_MSWIN_GETTIME_H_
#include "ll_internal.h"
#if HAVE__FTIME_S
# include <sys/timeb.h>
# include <sys/types.h>
# include <assert.h>
/**
* Retrieve the current system time on Windows.
*/
LL_DECLARE_INLINE void _ll_get_time
(
time_t *secondsp, ///< [out] Returned seconds since the Epoch.
unsigned long *microsecondsp ///< [out] Returned microseconds into the current second.
)
{
errno_t result;
struct _timeb now;
result = _ftime_s(&now);
assert(result == 0);
*secondsp = (time_t) now.time;
*microsecondsp = (unsigned long) now.millitm * 1000UL;
}
/**
* Retrieve the current system time.
*
* @param[out] secondsp Returned seconds since the Epoch.
* @param[out] microsecondsp Returned fraction of the current second, in microseconds.
*/
# define LL_GET_TIME(secondsp, microsecondsp) _ll_get_time((secondsp), (microsecondsp))
#endif /* end HAVE__FTIME_S */
#endif /* end PORT_MSWIN_GETTIME_H_ */
|
C |
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <assert.h>
// See "man strlcpy"
#include <bsd/string.h>
#include <string.h>
#include "hashmap.h"
// using pair functions from lecture
void
free_pair(hashmap_pair* pp)
{
if (pp) {
free(pp->key);
free(pp);
}
}
int
hash(char* key)
{
return strlen(key) * 67;
}
hashmap*
make_hashmap_presize(int nn)
{
hashmap* hh = calloc(1, sizeof(hashmap));
hh->capacity = nn;
hh->size = 0;
hh->data = calloc(nn, sizeof(hashmap_pair*));
return hh;
}
hashmap*
make_hashmap()
{
return make_hashmap_presize(4);
}
void
free_hashmap(hashmap* hh)
{
for (size_t ii = 0; ii < hh->capacity; ++ii) {
if (hh->data[ii]) {
free_pair(hh->data[ii]);
}
}
free(hh->data);
free(hh);
}
int
hashmap_has(hashmap* hh, char* kk)
{
return hashmap_get(hh, kk) != -1;
}
int
hashmap_get(hashmap* hh, char* kk)
{
long ii = hash(kk) & (hh->capacity - 1);
assert(ii >= 0 && ii < hh->size);
return hh->data[ii]->val;
}
void
hashmap_put(hashmap* hh, char* kk, int vv)
{
if (hh->size >= hh->capacity) {
hashmap_grow(hh);
}
long ii = hash(kk) & (hh->capacity - 1);
hh->data[ii] = calloc(hh->capacity, sizeof(hashmap_pair*));
hh->size += 1;
}
void
hashmap_del(hashmap* hh, char* kk)
{
long ii = hash(kk) & (hh->capacity - 1);
hashmap_pair** ref = &(hh->data[ii]);
hashmap_pair* curr = *ref;
free_pair(curr);
}
hashmap_pair
hashmap_get_pair(hashmap* hh, int ii)
{
assert(ii >= 0 && ii < hh->size);
hashmap_pair* ref = hh->data[ii];
return *ref;
}
void
hashmap_dump(hashmap* hh)
{
printf("== hashmap dump ==\n");
for (size_t ii = 0; ii < hh->capacity; ++ii) {
hashmap_pair pair = hashmap_get_pair(hh, ii);
if (hh->data[ii]) {
printf("%s, %d\n", pair.key, pair.val);
}
}
}
void
hashmap_grow(hashmap* hh)
{
size_t nn = hh->capacity;
hashmap_pair** data = hh->data;
hh->capacity = 2 * nn;
hh->data = calloc(hh->capacity, sizeof(hashmap_pair*));
}
|
C | /*
* File Name: file_read4.c
* Create Date: 2016年12月05日 星期一 11时20分13秒
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct readFF
{
int num;
char str[15];
struct readFF *next;
};
int
main ()
{
return 0;
}
void
readed ()
{
FILE *fp = NULL;
fp = fopen ();
if (NULL != fp)
{
int n;
getline ();
fclose (fp);
}
}
|
C | #include "ncurses.h"
/*
A_NORMAL нормальный, переустановка всего остального
A_STANDOUT наиболее яркий режим
A_UNDERLINE подчеркивание
A_REVERSE обратное изображение
A_BLINK мигание
A_DIM тусклый или полуяркий режим
A_BOLD жирный шрифт
A_ALTCHARSET использование альтернативной символьной таблицы
A_INVIS невидимый режим
A_PROTECT режим защиты
A_CHARTEXT маска для действующих символов (chtype)
A_COLOR маска для цвета
COLOR_PAIR(n) установка цветовой пары n
PAIR_NUMBER(a) получение цветовой пары, лежащей в атрибуте a
*/
int main()
{
const int max_x = 7;
const int max_y = max_x*max_x;
initscr();
curs_set(0);
const int width = 50;
const int height = 20;
if (!initscr())
{
fprintf(stderr, "Error initialising ncurses.\n");
exit(1);
}
int offsetx = (COLS - width) / 2;
int offsety = (LINES - height) / 2;
WINDOW *win = newwin(height, width, offsety, offsetx);
// Установка атрибутов для окна
wattron(win, A_BLINK | A_BOLD);
start_color(); // Инициализация цветов
char hello[] = "X";
if (has_colors() && COLOR_PAIRS >= 13)
{
int n = 1;
init_pair(1, COLOR_RED, COLOR_BLACK);
init_pair(2, COLOR_GREEN, COLOR_BLACK);
init_pair(3, COLOR_YELLOW, COLOR_BLACK);
init_pair(4, COLOR_BLUE, COLOR_BLACK);
init_pair(5, COLOR_MAGENTA, COLOR_BLACK);
init_pair(6, COLOR_CYAN, COLOR_BLACK);
init_pair(7, COLOR_BLUE, COLOR_WHITE);
init_pair(8, COLOR_WHITE, COLOR_RED);
init_pair(9, COLOR_BLACK, COLOR_GREEN);
init_pair(10, COLOR_BLUE, COLOR_YELLOW);
init_pair(11, COLOR_WHITE, COLOR_BLUE);
init_pair(12, COLOR_WHITE, COLOR_MAGENTA);
init_pair(13, COLOR_BLACK, COLOR_CYAN);
while (n <= 13)
{
color_set(n, NULL);
// wmove(win, (height-13)/2 + n, width/2);
mvaddstr(5 + n, (COLS-strlen(hello))/2, hello);
// waddch(win, 'Z' | COLOR_PAIR(n));
n++;
}
}
box(win, 0, 0);
getch();
endwin();
return (0);
} |
C | #include <logger.h>
#include <stdarg.h>
#include <stdint.h>
#include <string.h>
#include <kernel.h>
#include <serial.h>
#define PR_LJ 0x01
#define PR_CA 0x02
#define PR_SG 0x04
#define PR_64 0x08
#define PR_32 0x10
#define PR_WS 0x20
#define PR_LZ 0x40
#define PR_FP 0x80
#define PR_BUFLEN 32
int string_format(const char *fmt, va_list args, fnptr_t fn, void *ptr)
{
unsigned state, flags, radix, actual_wd, count, given_wd;
char *where, buf[PR_BUFLEN];
long num;
state = flags = count = given_wd = 0;
for (; *fmt; fmt++)
{
switch (state)
{
case 0:
if (*fmt != '%') /* not %... */
{
fn(*fmt, ptr); /* ...just echo it */
count++;
break;
}
state++;
fmt++;
/* FALL THROUGH */
case 1:
if (*fmt == '%') /* %% */
{
fn(*fmt, ptr);
count++;
state = flags = given_wd = 0;
break;
}
if (*fmt == '-')
{
if (flags & PR_LJ) /* %-- is illegal */
state = flags = given_wd = 0;
else
flags |= PR_LJ;
break;
}
state++;
if (*fmt == '0')
{
flags |= PR_LZ;
fmt++;
}
/* FALL THROUGH */
case 2:
if (*fmt >= '0' && *fmt <= '9')
{
given_wd = 10 * given_wd +
(*fmt - '0');
break;
}
state++;
/* FALL THROUGH */
case 3:
if (*fmt == 'F')
{
flags |= PR_FP;
break;
}
if (*fmt == 'N')
break;
if (*fmt == 'l')
{
flags |= PR_64;
break;
}
if (*fmt == 'h')
{
flags |= PR_32;
break;
}
state++;
/* FALL THROUGH */
case 4:
where = buf + PR_BUFLEN - 1;
*where = '\0';
switch (*fmt)
{
case 'X':
flags |= PR_CA;
/* FALL THROUGH */
case 'x':
case 'p':
flags |= PR_64;
__attribute__((fallthrough));
case 'n':
radix = 16;
goto DO_NUM;
case 'b':
radix = 2;
goto DO_NUM;
case 'd':
case 'i':
flags |= PR_SG;
/* FALL THROUGH */
case 'u':
radix = 10;
goto DO_NUM;
case 'o':
radix = 8;
DO_NUM:
if (flags & PR_64)
num = va_arg(args, int64_t);
else if (flags & PR_32)
{
if (flags & PR_SG)
num = va_arg(args, int32_t);
else
num = va_arg(args, uint32_t);
}
else
{
if (flags & PR_SG)
num = va_arg(args, int32_t);
else
num = va_arg(args, uint32_t);
}
if (flags & PR_SG)
{
if (num < 0)
{
flags |= PR_WS;
num = -num;
}
}
do
{
uint64_t temp;
temp = (uint64_t)num % radix;
where--;
if (temp < 10)
*where = temp + '0';
else if (flags & PR_CA)
*where = temp - 10 + 'A';
else
*where = temp - 10 + 'a';
num = (uint64_t)num / radix;
} while (num != 0);
goto EMIT;
case 'c':
flags &= ~PR_LZ;
where--;
*where = (char)va_arg(args, int);
actual_wd = 1;
goto EMIT2;
case 's':
flags &= ~PR_LZ;
where = va_arg(args, char *);
EMIT:
actual_wd = strlen(where);
if (flags & PR_WS)
actual_wd++;
if ((flags & (PR_WS | PR_LZ)) ==
(PR_WS | PR_LZ))
{
fn('-', ptr);
count++;
}
EMIT2:
if ((flags & PR_LJ) == 0)
{
while (given_wd > actual_wd)
{
fn(flags & PR_LZ ? '0' : ' ', ptr);
count++;
given_wd--;
}
}
if ((flags & (PR_WS | PR_LZ)) == PR_WS)
{
fn('-', ptr);
count++;
}
while (*where != '\0')
{
fn(*where++, ptr);
count++;
}
if (given_wd < actual_wd)
given_wd = 0;
else
given_wd -= actual_wd;
for (; given_wd; given_wd--)
{
fn(' ', ptr);
count++;
}
break;
default:
break;
}
__attribute__((fallthrough));
default:
state = flags = given_wd = 0;
break;
}
}
return count;
}
int serial_print(unsigned c, void *ptr __UNUSED__)
{
serial_transmit(c);
return 0;
}
void serial_log(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
(void)string_format(fmt, args, serial_print, NULL);
va_end(args);
} |
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* errors_free_close.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: yazhu <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/02/02 17:54:52 by yazhu #+# #+# */
/* Updated: 2018/02/06 19:35:18 by yazhu ### ########.fr */
/* */
/* ************************************************************************** */
#include "fdf.h"
int free_line_arr(char **line_arr, int return_value)
{
int j;
if (line_arr)
{
j = 0;
while (line_arr[j] != '\0')
ft_strdel(&line_arr[j++]);
free(line_arr);
}
return (return_value);
}
int close_free_and_exit(int fd, t_data *data, int return_value)
{
close(fd);
return (free_line_arr(data->map, return_value));
}
/*
** error [1] : no data in map
** error [2] : wrong line length
*/
int map_errors(int error, int fd, t_data *data)
{
if (error == 1)
ft_putstr("No data found.\n");
if (error == 2)
ft_putstr("Found wrong line length. Exiting\n");
free_line_arr(data->map, 0);
close(fd);
return (1);
}
int map_file_error(char *file_name)
{
ft_putstr("No file ");
ft_putendl(file_name);
return (1);
}
int usage_error(void)
{
ft_putstr("Usage : ./fdf <filename>\n");
return (1);
}
|
C | /*
* Program demonstrating the use of execl()
*/
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
extern int errno;
int main()
{
char buf[50];
int retVal;
int pid;
printf("The actual pid %d : %d \n",getpid(),getppid());
pid=fork();
if(pid==0)
{
printf("Child pid %d",getpid());
printf("Enter the path of Executable:");
scanf("%s",buf);
retVal = execl(buf,NULL); //replace the current process
if(retVal < 0) //image with the new procees image
printf("Error in exec: %s\n",strerror(errno));
else
printf("This line will not be printed\n");
}
else
{
wait(0);
printf("\nParent is exiting....%d ",getpid());
}
return 0;
}
|
C | #include "typedefs.h"
#include "tm4c123gh6pm.h"
#include "DIO.h"
#define HWREG(x) (*((volatile unsigned long *)(x)))
enum Dio_LevelType {
STD_LOW = 0 , STD_HIGH = 1
};
uint8 DIO_ReadPort(uint8 port_index , uint8 pins_mask)
{
switch (port_index)
{
case 0 :
return GPIO_PORTA_DATA_R & pins_mask;
break;
case 1 :
return GPIO_PORTB_DATA_R & pins_mask;
break;
case 2 :
return GPIO_PORTC_DATA_R & pins_mask;
break;
case 3 :
return GPIO_PORTD_DATA_R & pins_mask;
break;
case 4 :
return GPIO_PORTE_DATA_R & pins_mask;
break;
case 5 :
return GPIO_PORTF_DATA_R & pins_mask;
break;
}
return 0;
}
void DIO_WritePort1(unsigned char word,uint32 port, uint8 mask) {
word = word & (mask);
HWREG(port+0x3FC) = (word);
}
void DIO_WritePort(uint8 port_index , uint8 pins_mask , enum Dio_LevelType pins_level)
{
switch (port_index)
{
case 0 :
if (pins_level == STD_LOW)
{
GPIO_PORTA_DATA_R &= ~pins_mask;
}
else
{
GPIO_PORTA_DATA_R |= pins_mask;
}
break;
case 1 :
if (pins_level == STD_LOW)
{
GPIO_PORTB_DATA_R &= ~pins_mask;
}
else
{
GPIO_PORTB_DATA_R |= pins_mask;
}
break;
case 2 :
if (pins_level == STD_LOW)
{
GPIO_PORTC_DATA_R &= ~pins_mask;
}
else
{
GPIO_PORTC_DATA_R |= pins_mask;
}
break;
case 3 :
if (pins_level == STD_LOW)
{
GPIO_PORTD_DATA_R &= ~pins_mask;
}
else
{
GPIO_PORTD_DATA_R |= pins_mask;
}
break;
case 4 :
if (pins_level == STD_LOW)
{
GPIO_PORTE_DATA_R &= ~pins_mask;
}
else
{
GPIO_PORTE_DATA_R |= pins_mask;
}
break;
case 5 :
if (pins_level == STD_LOW)
{
GPIO_PORTF_DATA_R &= ~pins_mask;
}
else
{
GPIO_PORTF_DATA_R |= pins_mask;
}
break;
}
}
void DIO_FlipPort(uint8 port_index , uint8 pins_mask)
{
switch (port_index)
{
case 0 :
GPIO_PORTA_DATA_R ^= pins_mask;
break;
case 1 :
GPIO_PORTB_DATA_R ^= pins_mask;
break;
case 2 :
GPIO_PORTC_DATA_R ^= pins_mask;
break;
case 3 :
GPIO_PORTD_DATA_R ^= pins_mask;
break;
case 4 :
GPIO_PORTE_DATA_R ^= pins_mask;
break;
case 5 :
GPIO_PORTF_DATA_R ^= pins_mask;
break;
}
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_hex2int.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ssacrist <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/02 10:27:01 by ssacrist #+# #+# */
/* Updated: 2020/12/05 10:20:30 by ssacrist ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
** Take a hex string and convert it to a 32bit number (max 8 hex digits)
**
** 1. Get current character then increment (line 32).
** 2. Transform hex character to the 4bit equivalent number, using
** the ascii table indexes (lines 34 - 39).
** 3. Shift 4 to make space for new digit, and
** add the 4 bits of the new digit (line 41).
*/
uint32_t ft_hex2int(char *hex)
{
uint32_t val;
uint8_t byte;
val = 0;
while (*hex)
{
byte = *hex++;
if (byte >= '0' && byte <= '9')
byte = byte - '0';
else if (byte >= 'a' && byte <= 'f')
byte = byte - 'a' + 10;
else if (byte >= 'A' && byte <= 'F')
byte = byte - 'A' + 10;
val = (val << 4) | (byte & 0xF);
}
return (val);
}
|
C | #include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
int main() {
int pipe;
char * myfifo = "/tmp/myfifo";
mkfifo(myfifo, 0666);
char inputQuery[100] = {'\0'};
char result[3600];
char control;
while (1) {
// clean input
fflush(stdin);
printf("QUERY: ");
// write a query on pipe
fgets(inputQuery, 80, stdin);
pipe = open(myfifo, O_WRONLY);
write(pipe, inputQuery, strlen(inputQuery)+1);
close(pipe);
pipe = open(myfifo,O_RDONLY);
read(pipe,result,3600);
if (result[0] == '\0') {
printf("result is null/n");
break;
}else if(inputQuery[0] != '\0'){
printf("Do you want to save a query result (T/F) ? \n");
scanf("%c",&control);
if(control == 'T'){
pid_t process = fork();
if(process < 0){
printf("Process fail !!\n");
break;
}else if (process == 0){
char* arguments[] = {"/kaydet", result, NULL };
execv("/kaydet", arguments);
}else{
sleep(15);
}
}else if(control == 'F'){
printf("Signing out...\n");
break;
}
}
close(pipe);
}
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
void funcionBienvenida(char * nombre);
void funcionDespedida (char* nombre);
void fDelega(void(*punteroFuncion)(char* elDato),char * nombre);
//void funcionDespedidaSin(char* nombre);
///void funcionBienvenidaMas(char* nombre);
int main()
{
fDelega(funcionBienvenida,"NATALIA NATALIA");
getche();
fDelega(funcionDespedida,"NATALIA NATALIA");
getche();
//fDelega(funcionDespedidaSin,"NATALIA NATALIA");
//getche();
//fDelega(funcionBienvenidaMas,"NATALIA NATALIA");
// getche();
}
void funcionBienvenida(char* nombre )
{
printf("Bienvenida %s , a la empresa .", nombre);
}
void funcionDespedida(char * nombre)
{
printf("vos %s estas despedida ----->.",nombre);
}
void fDelega(void(*punteroFuncion)(char* elDato),char * nombre)
{
punteroFuncion(nombre);
}
|
C | #include<stdio.h>
int main ()
{
int N1, N2, N;
scanf ("%d.%d", &N1, &N2);
N = (N1*100)+N2;
printf("Notes:\n");
printf("%d note of TK 100.00\n", N/10000);
N = N % 10000;
printf("%d note of TK 50.00\n", N/5000);
N = N % 5000;
printf("%d note of TK 20.00\n", N/2000);
N = N % 2000;
printf("%d note of TK 10.00\n", N/1000);
N = N % 1000;
printf("%d note of TK 5.00\n", N/500);
N = N % 500;
printf("%d note of TK 2.00\n", N/200);
N = N % 200;
printf("\nCoins:\n");
printf("%d Coins of TK 1.00\n", N/100);
N = N % 100;
printf("%d Coins of TK 0.50\n", N/50);
N = N % 50;
printf("%d Coins of TK 0.25\n", N/25);
N = N % 25;
printf("%d Coins of TK 0.10\n", N/10);
N = N % 10;
printf("%d Coins of TK 0.05\n", N/5);
N = N % 5;
printf("%d Coins of TK 0.01\n", N/1);
N = N % 1;
return 0;
}
|
C | /**
* This file contains the search engine backend, for compilation to
* webassembly. This code uses the page data and the prefix tree stored in
* search.h, which are generated during the Python build process, to provide
* the actual search functionality.
*/
#include "search.h"
#define NULL 0
#define WORDS_MAX 64
#define INPUT_MAX_SIZE 1024
typedef unsigned int page_map_t;
/**
* A result struct, which hold the total calculated count
* of a page, and that pages index
*/
typedef struct RESULT {
page_i page;
page_map_t count;
} result_t;
/**
* The global variables and arrays used by the searcher.
*/
typedef struct GLOBALS {
/* The array containing the search result pages. */
result_t results[PAGE_COUNT];
int results_size;
/* Reusable words list. */
const char *words[WORDS_MAX];
int word_count;
/* Reusable page and temporary page maps. */
page_map_t map_a[PAGE_COUNT];
page_map_t map_b[PAGE_COUNT];
} globals_t;
/* Global variables. */
static globals_t g = {0};
/* The input buffer for communicating with javascript. */
char input_output[INPUT_MAX_SIZE];
/**
* Parse the input string to split it into words. This overwrites the input
* string, and adds the words to the global words vector.
*
* input: the input string to read from and write to.
*/
void parse_input(char *input) {
char *cleaned_it = input;
char *found_word = NULL;
/* Transform the input. */
for (char *input_it = input; *input_it; ++input_it) {
switch (*input_it) {
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
case 'Y': case 'Z':
/* Convert the letter to lower case. */
*input_it += 32;
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
case 's': case 't': case 'u': case 'v': case 'w': case 'x':
case 'y': case 'z': case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7': case '8': case '9':
/* Add this letter, and possibly start a new word. */
if (!found_word)
found_word = cleaned_it;
*(cleaned_it++) = *input_it;
break;
case ' ': case '\n': case '\t': case '\r':
/* Split into a new word. */
if (found_word) {
*(cleaned_it++) = '\0';
g.words[g.word_count++] = found_word;
found_word = NULL;
if (g.word_count == WORDS_MAX)
return;
}
break;
default:
/* Ignore other characters. */
break;
}
}
/* Add the last word. */
*cleaned_it = '\0';
if (found_word)
g.words[g.word_count++] = found_word;
}
/**
* Find a node which matches with the word, or NULL if no match can be found.
* The lookup is done in the prefix trie from search.h.
*
* word: the word to find.
*
* returns: the node directly or indirectly associated with the word.
*/
const node_t *find_node(const char *word) {
const node_t *current = nodes;
int progress = 0;
/* Iterate over the word to find the matching node. */
while (word[progress]) {
int match = 0;
for (child_s i = 0; i < current->child_count; i++) {
const node_t *child = nodes + current->children + i;
const char *str = chars + child->chars;
/* We have a match if the first character is the same. */
if (str[0] == word[progress]) {
match = 1;
/* Check if the rest of the str matches. */
for (str++, progress++; *str && word[progress];
str++, progress++) {
if (*str != word[progress]) {
/* This is not a match after all, return empty. */
return NULL;
}
}
/* Move to the next node. */
current = child;
break;
}
}
/* We can give up if no match has been found. */
if (!match)
return NULL;
}
return current;
}
/**
* Fill a page map with all the pages associated with a node and its children.
*/
void fill_page_map(const node_t *node, page_map_t *page_map) {
/* Add the pages of this node to the list. */
for (page_s i = 0; i < node->page_count; ++i) {
const page_t *page = pages + (node->pages + i);
page_map[page->index] += page->count;
}
/* Add the pages of all the children. */
for (child_s i = 0; i < node->child_count; ++i)
fill_page_map(nodes + node->children + i, page_map);
}
/**
* Fill a page map with all the pages which contain (a part of) a word.
*
* page_map: the page map to place the results in.
* word: the word to search.
*
* returns: 0 if no pages have been found, 1 if this word should be ignored,
* and 2 otherwise.
*/
int search_word(page_map_t *page_map, const char *word) {
/* Check if a matching node exists. */
const node_t *node = find_node(word);
if (node == NULL)
return -1;
/* Clear the page map. */
for (int i = 0; i < PAGE_COUNT; ++i)
page_map[i] = 0;
/* Now combine all of the pages starting from the found word node. */
fill_page_map(node, page_map);
/* Ignore this node, as it is a stopword. */
return node->pages == IGNORE_NODE_VALUE;
}
/**
* Search all the words of the global word stack, combine the results, and
* return the final page map.
*
* returns: a page map containing the results of the search.
*/
page_map_t *search_and_combine_words() {
page_map_t *page_map = g.map_a, *temp_map = g.map_b;
int page_map_empty = 1;
int added_non_stopword = 0;
/* Iterate over the words to fill the page map. */
for (int i = 0; i < g.word_count; ++i) {
int found_map = search_word(temp_map, g.words[i]);
if (found_map == -1) {
/* The word was not found, so there are no results. */
return NULL;
}
else {
if (page_map_empty) {
/* Replace the empty page map with the temp map. */
page_map_empty = 0;
page_map_t *temp = temp_map;
temp_map = page_map;
page_map = temp;
/* Half stopword contributions. */
if (found_map == 1) {
for (int i = 0; i < PAGE_COUNT; i++)
page_map[i] /= 2;
}
else
added_non_stopword = 1;
}
else if (found_map == 1 || !added_non_stopword) {
/* The word was a stopword, so union both maps. */
for (int i = 0; i < PAGE_COUNT; i++)
page_map[i] += temp_map[i] / 2;
}
else if (found_map == 0) {
if (!added_non_stopword) {
/* This is the first non-stopword, so use all its words. */
for (int i = 0; i < PAGE_COUNT; i++)
page_map[i] += temp_map[i];
added_non_stopword = 1;
}
else {
/* Intersect the two maps, adding the two counts only if
* the page exists in both maps. */
for (int i = 0; i < PAGE_COUNT; i++) {
if (page_map[i] && temp_map[i])
page_map[i] += temp_map[i];
else
page_map[i] = 0;
}
}
}
}
}
/* Return the page map if it is not empty. */
return page_map_empty ? NULL : page_map;
}
/**
* Get the memory location of input/output buffer. This is used to
* get the buffer in the Javascript code.
*/
__attribute__((export_name("getIOBuffer")))
char *get_io_buffer() {
return input_output;
}
/**
* Get the size of the input/output buffer. This is used to
* get the buffer in the Javascript code.
*/
__attribute__((export_name("getIOBufferSize")))
int get_io_buffer_size() {
return INPUT_MAX_SIZE;
}
/**
* Perform the search on an input query and store the found
* page entries in memory.
*
* input: the input string.
*/
__attribute__((export_name("performSearch")))
void perform_search() {
/* Clear the previous search. */
g.results_size = 0;
g.word_count = 0;
/* Parse the input and create the page map. */
parse_input(input_output);
page_map_t *page_map = search_and_combine_words();
/* Update the result array if the page map is not empty. */
if (page_map) {
/* Add the final page map contents to the results vector. */
for (int i = 0; i < PAGE_COUNT; ++i) {
if (page_map[i] != 0)
g.results[g.results_size++] = (result_t){i, page_map[i]};
}
}
}
/**
* Return the next found page as a url, title, and section title.
*
* returns: a url, title and section title of a page, seperated by newlines.
*/
__attribute__((export_name("getSearch")))
int get_search() {
/* Return 0 if no results are left. */
if (g.results_size == 0)
return 0;
/* Get the highest result from the result array. */
int max_i = 0, max_count = 0;
for (int i = 0; i < g.results_size; i++) {
if (g.results[i].count > max_count) {
max_count = g.results[i].count;
max_i = i;
}
}
/* Get the next entry from the array. */
g.results[max_i].count = 0;
const char *result_it = urltitles[g.results[max_i].page];
/* Remove already returned results from the back. */
int temp = g.results_size;
while (g.results_size != 0 && g.results[--temp].count == 0) {
g.results_size = temp;
}
/* Copy the output to the input_output and return its length. */
int i;
for (i = 0; *result_it; ++result_it, ++i) {
input_output[i] = *result_it;
}
return i;
}
#ifdef RUN_LOCAL
#include <stdlib.h>
#include <stdio.h>
/**
* This is main function for if we are running the search locally. The search query
* can then be given as command line arguments. This is mainly used for testing
* purposes.
*
* n: the number of arguments
* input: an array of the arguments.
*
* returns: 0.
*/
int main(int n, char **input) {
/* Fill the buffer with the input strings. */
char *buffer_it = input_output;
for (int i = 1; i < n; i++) {
for (char *str = input[i]; *str; ++str)
*(buffer_it++) = *str;
if (i != n - 1)
*(buffer_it++) = ' ';
}
*(buffer_it++) = 0;
/* Search the query. */
printf("Results for [%s]\n", input_output);
perform_search();
/* Print the results. */
int length;
while ((length = get_search())) {
input_output[length] = 0;
printf("%s\n", input_output);
}
return 0;
}
#endif
|
C | #include "binary_trees.h"
/**
*binary_tree_insert_right - Inserts a node as the right-child of another node
*@parent: is a pointer to the node to insert the right-child in
*@value: is the value to store in the new node
*Return: A pointer to the new node
*/
binary_tree_t *binary_tree_insert_right(binary_tree_t *parent, int value)
{
binary_tree_t *current_n;
if (!parent)
return (NULL);
current_n = malloc(sizeof(binary_tree_t));
if (!current_n)
return (NULL);
current_n->n = value;
current_n->left = NULL;
current_n->right = NULL;
if (parent->right != NULL)
{
current_n->right = parent->right;
current_n->right->parent = current_n;
current_n->parent = parent;
parent->right = current_n;
}
else
{
parent->right = current_n;
current_n->parent = parent;
}
return (current_n);
}
|
C | #include "linkedlist.h"
#include <stdio.h>
#include <stdlib.h>
/* reference solution provided with assignment description */
void ll_show(ll_node *list) {
ll_node *ptr = ll_head(list);
putchar('[');
while(ptr) {
if (ptr->prev) printf(", ");
if (ptr == list) putchar('*');
printf("%d", ptr->value);
if (ptr == list) putchar('*');
ptr = ptr->next;
}
puts("]");
}
/**
* Returns a pointer to the first node of a list, given a pointer to any node
* in the list. If the provided pointer is `NULL`, instead returns `NULL`.
*/
ll_node *ll_head(ll_node *list) {
if(!list) {
return NULL;
}
ll_node *curNode = list;
while(curNode->prev != NULL) {
curNode = curNode->prev;
}
return curNode;
}
/**
* Returns a pointer to the last node of a list, given a pointer to any node
* in the list. If the provided pointer is `NULL`, instead returns `NULL`.
*/
ll_node *ll_tail(ll_node *list) {
if(!list) {
return NULL;
}
ll_node *curNode = list;
while(curNode->next != NULL) {
curNode = curNode->next;
}
return curNode;
}
/**
* Returns the number of nodes in the list, which is the same for all nodes
* in the list and 0 for `NULL`.
*/
unsigned long ll_length(ll_node *list) {
if(!list) {
return 0;
}
ll_node *ptr = ll_head(list);
int count = 1;
while(ptr->next != NULL) {
ptr = ptr->next;
count ++;
}
return count;
}
/**
* Given a pointer to a node in a list, returns a pointer to the first node
* at or after that node which has the given `value`. If given `NULL`, or
* if no such node exists, returns `NULL`.
*/
ll_node *ll_find(ll_node *list, int value) {
if(!list) {
return NULL;
}
ll_node *curNode = list;
if(curNode->value == value) {
return list;
}
else {
while(curNode->next != NULL) {
curNode = curNode->next;
if(curNode->value == value) {
return curNode;
}
}
}
return NULL;
}
/**
* Given a pointer to a node in a list, remove that node from the list,
* `free`ing its memory in the process. Returns a pointer to the node that now
* occupies the same position in the list that the removed node used to occupy
* (which may be `NULL` if the removed node was the last node in the list).
*
* If given `NULL`, this function does nothing and returns `NULL`.
*/
ll_node *ll_remove(ll_node *list) {
if(!list) {
return NULL;
}
//Add Corner case if there is only one node
ll_node *newCurNode = list->next;
ll_node *prevNode = list->prev;
prevNode->next = newCurNode;
free(list);
return newCurNode;
}
/**
* Extend a list by one by adding `value` next to `list`. If `before` is 0,
* inserts `value` immediately following the node pointed to by `list`;
* otherwise inserts `value` immediately before that node. If `list` is NULL,
* the newly inserted node is the entire list. In all cases, the new node is
* allocated using `malloc` and returned by the function.
*/
ll_node *ll_insert(int value, ll_node *list, int before) {
if(!list) {
ll_node *newNode = malloc(sizeof(ll_node));
list = newNode;
list->value = value;
list->next = NULL;
list->prev = NULL;
return list;
}
ll_node *newNode = malloc(sizeof(ll_node));
if(before == 0) {
newNode->value = value;
newNode->next = list->next;
newNode->prev = list;
if(list->next != NULL) {
list->next->prev = newNode;
}
list->next = newNode;
}
else {
newNode->value = value;
newNode->next = list;
newNode->prev = list->prev;
if (list->prev != NULL) {
list->prev->next = newNode;
}
list->prev = newNode;
}
return newNode;
} |
C | #include <stdio.h>
int ischar(char c){
int r;
r=-1;
if((c>='A') && (c<='Z')) r=1;
if((c>='a') && (c<='z')) r=1;
return(r);
}
int main(){
char s[1024];
int sl,i,H,A[256];
while (gets(s)){
sl=strlen(s);
for(i=0;i<256;i++)
A[i]=0;
H=0;
for(i=0;i<sl;i++)
{
if(ischar(s[i])==1) A[s[i]]++;
if(A[s[i]]>H)H=A[s[i]];
}
for(i=0;i<256;i++)
if(A[i]==H)printf("%c",i);
printf(" %d\n",H);
}
}
|
C | #ifndef _DLIST_H_
#define _DLIST_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdbool.h>
#define DataType int
typedef struct DListNode
{
struct DListNode *prev;
DataType data;
struct DListNode *next;
}DListNode;
typedef struct DList
{
DListNode *first;
DListNode *last;
size_t size;
}DList;
void DListInit(DList *plist);
void DListShow(DList *plist);
bool DListPushBack(DList *plist, DataType x);
bool DListPushFront(DList *plist, DataType x);
bool DListPopBack(DList *plist);
bool DListPopFront(DList *plist);
DListNode* DListFindByVal(DList *plist, DataType key);
bool DListDeleteByVal(DList *plist, DataType key);
size_t DListLength(DList *plist);
void DListClear(DList *plist);
void DListDestroy(DList *plist);
void DListReverse(DList *plist);
void DListInsertByVal(DList *plist, DataType x);
void DListSort(DList *plist);
bool DListModifyByVal(DList *plist, DataType key, DataType x);
#endif /*_DLIST_H_*/ |
C | #include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <malloc.h>
enum SymbolCodes
{
// Перечесление кодов символов для функции ввода строки
BACKSPACE_KEY = 8,
START_CHAR_RANGE = 32,
END_CHAR_RANGE = 126
};
enum OperationsCodes
{
// Перечисление кодов операций для организации главного меню.
KEYBOARD_INPUT = 1,
SHOW = 2,
TASK = 3,
CONSOLE_OUTPUT = 4,
QUIT = 5
};
enum Sizes
{
// Перечисление наибольших размеров массивов.
INPUT_SIZE = 100,
TOKEN_NAME_SIZE = 20
};
char* StrDynInput()
{
// Функция для ввода строки без указания длины
// источник - Лекция 3. Строки. Массивы строк. Операции над строками.pdf
char* userStr = (char*) malloc(1 * sizeof(char));
userStr[0] = '\0';
char curChar = 0;
int curSize = 1;
while (curChar != '\n')
{
curChar = getchar();
int deltaVal = 0; // Определяет, на сколько изменится длина массива
int lengthDif = 0;
// Если мы ситраем символы, а не пишем их,
if (curChar == BACKSPACE_KEY)
{
deltaVal = -1; // то будем уменьшать длину массива
lengthDif = 1; // и копировать строку до предпоследнего символа
}
// Иначе проверяем, входит ли введённый символ в диапазон печатных
else
{
if (curChar >= START_CHAR_RANGE && curChar <=
END_CHAR_RANGE)
{
deltaVal = 1; // Если да, то будем увеличиватьдлину на 1
lengthDif = 2; // Не заполняем последние 2 символа -
// оставлем мето для введённого символа и 0
}
else
{
continue;
} // Если это не печатный символ, то пропускаем его
}
// Если стирать больше нечего, но пользователь всё равно жмёт Backspace,
int newSize = curSize + deltaVal;
if (newSize == 0)
{
continue;
} // то мы переходим на следующую итерацию - ждём '\n'
char* tmpStr = (char*) malloc(newSize * sizeof(char));
if (tmpStr) // Проверяем, выделилась ли память
{
// Идём до предпоследнего символа, т.к. надо в конец записать 0
for (int i = 0; i < newSize - lengthDif; ++i)
{
tmpStr[i] = userStr[i];
}
if (curChar != BACKSPACE_KEY)
{// Если введён печатный символ,
tmpStr[newSize - 2] = curChar; // Добавляем его в строку
}
tmpStr[newSize - 1] = '\0';
free(userStr);
userStr = tmpStr;
curSize = newSize;
}
else
{
printf("Couldn't allocate memory!");
break;
}
}
return userStr;
}
char* CycleInputString(char* stringToOutput, bool(* pChecker)(char*))
{
// Функция для ввода строки с проверкой ввода.
//
// char* stringToOutput - строка, которую нужно выводить
// ... в запросе ввода;
// bool(* pChecker)(char*) - указатель на функцию, проверяющую
// ... дополнительные условия.
printf("%s\n", stringToOutput);
char* stringToReturn;
while (true)
{
stringToReturn = StrDynInput();
if (pChecker(stringToReturn))
{
return stringToReturn;
}
printf("Wrong format!\n");
free(stringToReturn);
}
}
int CycleInputInt(char* stringToOutput, bool(* pChecker)(int))
{
// Функция для ввода целого числа с проверкой ввода.
//
// char* stringToOutput - строка, которую нужно выводить
// ... в запросе ввода;
// bool(* pChecker)(int) - указатель на функцию, проверяющую
// ... дополнительные условия.
int number; // Необходимое число
int position; // Позиция числа в введенной строке
char input[INPUT_SIZE]; // Строка для ввода
// Считывает и проверяет ввод по нескольким условиям, до тех пор,
// пока не будет введено корректно.
while (true)
{
printf("%s\n", stringToOutput);
fflush(stdout);
char* fgetsRet = fgets(input, INPUT_SIZE, stdin);
if (fgetsRet == NULL)
{
printf("Wrong format!\n");
continue;
}
int inputLength = strlen(input) - 1;
input[inputLength] = '\0';
int sscanfRet = sscanf(input, "%d%n", &number, &position);
if (position != inputLength)
{
printf("Wrong format!\n");
continue;
}
if (pChecker && !pChecker(number))
{
printf("Wrong format!\n");
continue;
}
if (sscanfRet == 1) break;
printf("Wrong format!\n");
}
return number;
}
bool MainMenuInputChecker(int operationCode)
{
// Функция для вызова в функциях ввода с проверкой.
// ... Возвращает true, если введенное значение может быть
// значением кода операции в меню.
//
// int operationCode - число, которое нужно проверить.
return operationCode >= KEYBOARD_INPUT && operationCode <= QUIT;
}
bool MathCharsInputChecker(char* stringToCheck)
{
// Функция для вызова в функциях ввода с проверкой.
// ... Возвращает true, если введенное значение может быть
// строкой только с числами или с определенными символами.
//
// char* stringToCheck - число, которое нужно проверить.
for (int i = 0; i < strlen(stringToCheck); i++)
{
char k = stringToCheck[i];
if (!(k >= '(' && k <= '9' && k != ','))
{
return false;
}
}
return true;
}
typedef struct
{
// Структура для хранения токенов.
char tokenName[TOKEN_NAME_SIZE]; // Название токена
char content; // Значение токена
} SomeToken;
typedef struct
{
// Структура для хранения строки и её длины
char* content; // Строка
bool isFilled; // true, если выделена память
int length; // Длина строки
} DynStr;
typedef struct
{
// Структура для хранения динамического массива токенов
SomeToken* content; // Массив
bool isFilled; // true, если выделана память
} DynArrTokens;
void FreeDynArrStr(DynStr* arrToClean)
{
// Функция для очистки памяти, выделенной под arrToClean
if (arrToClean->isFilled)
{
free(arrToClean->content);
arrToClean->isFilled = false;
}
arrToClean->length = 0;
}
void FreeDynArrTokens(DynArrTokens* arrToClean)
{
// Функция для очистки памяти, выделенной под arrToClean
if (arrToClean->isFilled)
{
free(arrToClean->content);
arrToClean->isFilled = false;
}
}
int main()
{
DynStr objStr;
objStr.isFilled = false;
objStr.length = 0;
DynArrTokens tokens;
tokens.isFilled = false;
int operationCode;
while (true)
{
printf("\n1. Enter the string with keyboard.\n"
"2. Show the object string.\n"
"3. Perform the task.\n"
"4. Print result to the console.\n"
"5. Quit.\n\n");
operationCode = CycleInputInt(
"Choose the command and enter its number",
MainMenuInputChecker);
// Ввод строки к анализу с клавиатуры
if (operationCode == KEYBOARD_INPUT)
{
FreeDynArrStr(&objStr);
FreeDynArrTokens(&tokens);
objStr.content = CycleInputString("Enter string to analyze",
&MathCharsInputChecker);
objStr.isFilled = true;
objStr.length = strlen(objStr.content);
}
// Вывод строки к анализу в консоль
if (operationCode == SHOW)
{
if (objStr.isFilled)
{
printf("%s", objStr.content);
}
else
{
printf("No object string!\n");
}
}
// Выполнение анализа
if (operationCode == TASK)
{
FreeDynArrTokens(&tokens);
if (!objStr.isFilled)
{
printf("No object string!\n");
}
else
{
// Выделение памяти под массив токенов
tokens.content = (SomeToken*) malloc(
objStr.length * sizeof(SomeToken*));
tokens.isFilled = true;
for (int i = 0; i < objStr.length; i++)
{
// Непосредственно анализ
if (objStr.content[i] >= '0' && objStr.content[i] <= '9')
{
tokens.content[i].content = objStr.content[i];
strcpy(tokens.content[i].tokenName, "DIGIT");
}
if (objStr.content[i] == '/')
{
tokens.content[i].content = objStr.content[i];
strcpy(tokens.content[i].tokenName, "DIVISION");
}
if (objStr.content[i] == '.')
{
tokens.content[i].content = objStr.content[i];
strcpy(tokens.content[i].tokenName, "DOT");
}
if (objStr.content[i] == '+')
{
tokens.content[i].content = objStr.content[i];
strcpy(tokens.content[i].tokenName, "PLUS");
}
if (objStr.content[i] == '-')
{
tokens.content[i].content = objStr.content[i];
strcpy(tokens.content[i].tokenName, "MINUS");
}
if (objStr.content[i] == '*')
{
tokens.content[i].content = objStr.content[i];
strcpy(tokens.content[i].tokenName, "MULTIPL");
}
if (objStr.content[i] == ')')
{
tokens.content[i].content = objStr.content[i];
strcpy(tokens.content[i].tokenName, "CLOSE_PARANTH");
}
if (objStr.content[i] == '(')
{
tokens.content[i].content = objStr.content[i];
strcpy(tokens.content[i].tokenName, "OPEN_PARANTH");
}
}
}
}
// Вывод результатов анализа в консоль
if (operationCode == CONSOLE_OUTPUT)
{
if (!tokens.isFilled)
{
printf("No results for current string!\n");
}
else
{
for (int i = 0; i < objStr.length; i++)
{
printf("%s, %c\n", tokens.content[i].tokenName,
tokens.content[i].content);
}
}
}
// Выход из меню
if (operationCode == QUIT)
{
break;
}
}
// Очистка памяти и завершение программы
FreeDynArrStr(&objStr);
FreeDynArrTokens(&tokens);
return 0;
} |
C | #include "DHT.h"
#define DHTPIN 8 // what pin we're connected to
#define DHTTYPE DHT11 // DHT 11
DHT dht(DHTPIN, DHTTYPE);
void setup () {
Serial.begin(9600);
dht.begin;
}
void loop() {
if (Serial.available()) {
int ch = Serial.read();
if ( ch == '1' ) {
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print(h);
Serial.print(",");
Serial.println(t);
} else {
delay(10);
}
}
}
|
C | #include <stdio.h>
#include <string.h>
void main(void)
{
char livro[128] = "Este texto será perdido com a cópia";
strcpy(livro, "Programação C/C++");
printf("Nome do livro: %s\n", livro);
}
|
C | /*
** create.c for create.c in /Users/taing_k/Desktop/octo/taing_k
**
** Made by TAING Kevin
** Login <[email protected]>
**
** Started on Fri Jan 22 16:05:20 2016 TAING Kevin
** Last update Fri Jan 22 16:05:46 2016 TAING Kevin
*/
#include "libmy.h"
#include "struct.h"
void createMap(void)
{
t_maze maze;
my_putstr("Choose the width and the height of your maze :\n");
my_putstr("width : ");
maze.width = readNumber(4);
my_putstr("height : ");
maze.height = readNumber(4);
maze.tab = allocMap(maze.width, maze.height);
fillMap(maze);
editMap(maze);
free(maze.tab);
}
void fillMap(t_maze maze)
{
int i;
int j;
for (i = 0; i < maze.width; i++)
for (j = 0; j < maze.height; j++)
maze.tab[i][j] = '#';
maze.tab[0][0] = '8';
}
void saveMap(t_maze maze)
{
int file;
int i;
int j;
char *name;
name = nbToStr(nbFiles("maps/") + 1);
i = my_strlen(name);
my_strcpy(name + i, " - custom");
file = open(my_strcat(my_strdup("maps/"), name),
O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU | S_IRWXG | S_IRWXO);
for (i = 0; i < maze.height; i++)
{
for (j = 0; j < maze.width; j++)
{
if (maze.tab[j][i] == '8')
maze.tab[j][i] = 'S';
write(file, &maze.tab[j][i], 1);
}
write(file, "\n", 1);
}
free(name);
}
void editMap(t_maze maze)
{
char c;
int mode;
c = 0;
mode = 1;
while (c != 'c' && c != 'x' && c != 'C' && c != 'X')
{
disp(maze, 0);
emptyBuffer(c = getchar());
if (c == 'z' || c == 'Z')
mode = (mode == 3 ? 1 : mode + 1);
move(maze, c, mode);
}
if (c == 'x' || c == 'X')
saveMap(maze);
}
|
C | #include "test-squash.h"
struct BoundsInfo {
SquashCodec* codec;
uint8_t* compressed;
size_t compressed_length;
};
static void*
squash_test_bounds_setup(MUNIT_UNUSED const MunitParameter params[], void* user_data) {
struct BoundsInfo* info = munit_new (struct BoundsInfo);
info->codec = squash_get_codec (munit_parameters_get(params, "codec"));
munit_assert_not_null (info->codec);
info->compressed_length = squash_codec_get_max_compressed_size (info->codec, LOREM_IPSUM_LENGTH);
munit_assert_size (info->compressed_length, >=, LOREM_IPSUM_LENGTH);
info->compressed = munit_malloc(info->compressed_length);
SquashStatus res =
squash_codec_compress (info->codec,
&(info->compressed_length), info->compressed,
LOREM_IPSUM_LENGTH, LOREM_IPSUM, NULL);
SQUASH_ASSERT_OK (res);
uint8_t* p = realloc (info->compressed, info->compressed_length);
if (p != NULL) {
info->compressed = p;
}
return info;
}
static void
squash_test_bounds_tear_down(void* user_data) {
struct BoundsInfo* info = (struct BoundsInfo*) user_data;
munit_assert_not_null (info);
free (info->compressed);
free (info);
}
static MunitResult
squash_test_bounds_decode_exact(MUNIT_UNUSED const MunitParameter params[], void* user_data) {
struct BoundsInfo* info = (struct BoundsInfo*) user_data;
munit_assert_not_null (info);
size_t decompressed_length = LOREM_IPSUM_LENGTH;
uint8_t* decompressed = munit_malloc(decompressed_length);
SquashStatus res =
squash_codec_decompress (info->codec,
&decompressed_length, decompressed,
info->compressed_length, info->compressed, NULL);
SQUASH_ASSERT_OK(res);
munit_assert_size(LOREM_IPSUM_LENGTH, ==, decompressed_length);
munit_assert_memory_equal(LOREM_IPSUM_LENGTH, decompressed, LOREM_IPSUM);
free (decompressed);
return MUNIT_OK;
}
static MunitResult
squash_test_bounds_decode_small(MUNIT_UNUSED const MunitParameter params[], void* user_data) {
struct BoundsInfo* info = (struct BoundsInfo*) user_data;
munit_assert_not_null (info);
/* *Almost* enough */
size_t decompressed_length = (size_t) LOREM_IPSUM_LENGTH - 1;
uint8_t* decompressed = munit_malloc(decompressed_length);
SquashStatus res =
squash_codec_decompress (info->codec,
&decompressed_length, decompressed,
info->compressed_length, info->compressed, NULL);
munit_assert_int(res, <, 0);
free (decompressed);
return MUNIT_OK;
}
static MunitResult
squash_test_bounds_decode_tiny(MUNIT_UNUSED const MunitParameter params[], void* user_data) {
struct BoundsInfo* info = (struct BoundsInfo*) user_data;
munit_assert_not_null (info);
/* Between 1 and length - 1 bytes (usually way too small) */
size_t decompressed_length = (size_t) munit_rand_int_range(1, LOREM_IPSUM_LENGTH - 1);
uint8_t* decompressed = munit_malloc(decompressed_length);
SquashStatus res =
squash_codec_decompress (info->codec,
&decompressed_length, decompressed,
info->compressed_length, info->compressed, NULL);
munit_assert_int(res, <, 0);
free (decompressed);
return MUNIT_OK;
}
static MunitResult
squash_test_bounds_decode_truncated(MUNIT_UNUSED const MunitParameter params[], void* user_data) {
struct BoundsInfo* info = (struct BoundsInfo*) user_data;
munit_assert_not_null (info);
/* These codecs fail, we're working on getting the fixed. */
const char* codec_name = squash_codec_get_name (info->codec);
if (strcmp (codec_name, "fastlz") == 0 ||
strcmp (codec_name, "wflz") == 0 ||
strcmp (codec_name, "wflz-chunked") == 0)
return MUNIT_SKIP;
/* Attempt to decode a truncated valid buffer, mostly as an attempt
to trick the codec into reading outside the provided buffer (ASAN
should pick it up). */
info->compressed_length -= munit_rand_int_range (1, (int) info->compressed_length - 1);
info->compressed = realloc (info->compressed, info->compressed_length);
size_t decompressed_length = LOREM_IPSUM_LENGTH;
uint8_t* decompressed = munit_malloc(decompressed_length);
squash_codec_decompress (info->codec,
&decompressed_length, decompressed,
info->compressed_length, info->compressed, NULL);
free (decompressed);
return MUNIT_OK;
}
static MunitResult
squash_test_bounds_encode_exact(MUNIT_UNUSED const MunitParameter params[], void* user_data) {
struct BoundsInfo* info = (struct BoundsInfo*) user_data;
munit_assert_not_null (info);
size_t compressed_length = info->compressed_length;
uint8_t* compressed = munit_malloc(compressed_length);
squash_codec_compress (info->codec,
&compressed_length, compressed,
LOREM_IPSUM_LENGTH, LOREM_IPSUM, NULL);
/* It's okay if some codecs require a few extra bytes to *compress*,
as long as they don't write outside the buffer they were provided,
so don't check the return value here. */
free(compressed);
return MUNIT_OK;
}
static MunitResult
squash_test_bounds_encode_small(MUNIT_UNUSED const MunitParameter params[], void* user_data) {
struct BoundsInfo* info = (struct BoundsInfo*) user_data;
munit_assert_not_null (info);
size_t compressed_length = info->compressed_length - 1;
uint8_t* compressed = munit_malloc(compressed_length);
SquashStatus res =
squash_codec_compress (info->codec,
&compressed_length, compressed,
LOREM_IPSUM_LENGTH, LOREM_IPSUM, NULL);
munit_assert_int(res, <, 0);
free(compressed);
return MUNIT_OK;
}
static MunitResult
squash_test_bounds_encode_tiny(MUNIT_UNUSED const MunitParameter params[], void* user_data) {
struct BoundsInfo* info = (struct BoundsInfo*) user_data;
munit_assert_not_null (info);
size_t compressed_length = munit_rand_int_range (1, info->compressed_length - 1);
uint8_t* compressed = munit_malloc(compressed_length);
SquashStatus res =
squash_codec_compress (info->codec,
&compressed_length, compressed,
LOREM_IPSUM_LENGTH, LOREM_IPSUM, NULL);
munit_assert_int(res, <, 0);
free(compressed);
return MUNIT_OK;
}
MunitTest squash_bounds_tests[] = {
{ (char*) "/decode/exact", squash_test_bounds_decode_exact, squash_test_bounds_setup, squash_test_bounds_tear_down, MUNIT_TEST_OPTION_NONE, SQUASH_CODEC_PARAMETER },
{ (char*) "/decode/small", squash_test_bounds_decode_small, squash_test_bounds_setup, squash_test_bounds_tear_down, MUNIT_TEST_OPTION_NONE, SQUASH_CODEC_PARAMETER },
{ (char*) "/decode/tiny", squash_test_bounds_decode_tiny, squash_test_bounds_setup, squash_test_bounds_tear_down, MUNIT_TEST_OPTION_NONE, SQUASH_CODEC_PARAMETER },
{ (char*) "/decode/truncated", squash_test_bounds_decode_truncated, squash_test_bounds_setup, squash_test_bounds_tear_down, MUNIT_TEST_OPTION_NONE, SQUASH_CODEC_PARAMETER },
{ (char*) "/encode/exact", squash_test_bounds_encode_exact, squash_test_bounds_setup, squash_test_bounds_tear_down, MUNIT_TEST_OPTION_NONE, SQUASH_CODEC_PARAMETER },
{ (char*) "/encode/small", squash_test_bounds_encode_small, squash_test_bounds_setup, squash_test_bounds_tear_down, MUNIT_TEST_OPTION_NONE, SQUASH_CODEC_PARAMETER },
{ (char*) "/encode/tiny", squash_test_bounds_encode_tiny, squash_test_bounds_setup, squash_test_bounds_tear_down, MUNIT_TEST_OPTION_NONE, SQUASH_CODEC_PARAMETER },
{ NULL, NULL, NULL, NULL, MUNIT_TEST_OPTION_NONE, NULL }
};
MunitSuite squash_test_suite_bounds = {
(char*) "/bounds",
squash_bounds_tests,
NULL,
1,
MUNIT_SUITE_OPTION_NONE
};
|
C | /*
rvore binria
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct pessoa{
char nome[25];
int idade;
char endereco[50];
struct pessoa *esquerda, *direita;
}pessoa;
pessoa *criaPessoa(char nome[25], int idade, char endereco[50]);
void insereArvore( pessoa **raiz, pessoa *folha);
void mostraNoh(pessoa *noh);
void mostraArvore(pessoa *raiz);
void mostraPreOrdem(pessoa *raiz);
void mostrarEDR(pessoa *raiz);
int menu();
pessoa *localizaNoh(pessoa *arvore, char nome[25]);
int main()
{
char nome[25];
char endereco[50];
int idade;
pessoa *raiz=NULL;
pessoa *aux;
while(1)
{
switch(menu())
{
case 1: printf("\nIdade:");
scanf("%i",&idade);
printf("\nNome:");
scanf("%s",nome);
printf("\nEndereco:");
scanf("%s",endereco);
insereArvore(&raiz,criaPessoa(nome,idade,endereco));
break;
case 2: mostraArvore(raiz);
break;
case 3: mostraPreOrdem(raiz);
break;
case 4: mostrarEDR(raiz);
break;
case 5: printf("Valor desejado na consulta: ");
scanf("%s",nome);
aux = localizaNoh(raiz,nome);
mostraNoh(aux);
break;
case 6: return 0;
}
}
return 0;
}
int menu()
{
int opc;
printf("1-INSERIR \n");
printf("2-MOSTRAR EM ORDEM\n");
printf("3-MOSTRAR EM PRE ORDEM\n");
printf("4-MOSTRAR EDR\n");
printf("5-LOCALIZAR\n");
printf("6-SAIR\n");
printf("?:");
scanf("%i",&opc);
return opc;
}
pessoa *criaPessoa(char nome[25], int idade, char endereco[50]){
pessoa *p = (pessoa *) malloc (sizeof(pessoa));
p->idade = idade;
strcpy(p->nome, nome);
strcpy(p->endereco, endereco);
p->esquerda = p->direita = NULL;
return p;
}
void insereArvore( pessoa **raiz, pessoa *folha)
{
if(!*raiz)
{
*raiz = folha;
}
else if ((strcmp((*raiz)->nome,folha->nome))>0)
insereArvore(&(*raiz)->esquerda, folha);
else if ((strcmp((*raiz)->nome, folha->nome))<0)
insereArvore(&(*raiz)->direita, folha);
}
void mostraNoh(pessoa *noh)
{
printf("endereco noh...........: %p\n",noh);
printf("endereco noh a direita.: %p\n",noh->direita);
printf("endereco noh a esquerda: %p\n",noh->esquerda);
printf("nome...................: %s\n",noh->nome);
printf("idade..................: %d\n",noh->idade);
printf("endereco...............: %s\n\n",noh->endereco);
}
void mostraArvore(pessoa *raiz)
{
if(raiz){
mostraArvore(raiz->esquerda);
mostraNoh(raiz);
mostraArvore(raiz->direita);
}
}
void mostraPreOrdem(pessoa *raiz)
{
if(raiz)
{
mostraNoh(raiz);
mostraPreOrdem(raiz->esquerda);
mostraPreOrdem(raiz->direita);
}
}
void mostrarEDR(pessoa* raiz)
{
if(raiz)
{
mostrarEDR(raiz->esquerda);
mostrarEDR(raiz->direita);
mostraNoh(raiz);
}
}
pessoa *localizaNoh(pessoa *arvore, char nome[25])
{
if (arvore)
{
if (!strcmp(arvore->nome, nome))
return arvore;
else if (strcmp(arvore->nome, nome)>0)
return localizaNoh(arvore->esquerda,nome);
else if (strcmp(arvore->nome, nome)<0)
return localizaNoh(arvore->direita,nome);
else return NULL;
}
}
|
C | #define _POSIX_C_SOURCE 199309L
#include <stdio.h>
#include <stdlib.h>
#include "sift.h"
#include <time.h>
/********************************
Author: Sravanthi Kota Venkata
********************************/
void normalizeImage(F2D *image) {
int i;
int rows;
int cols;
int tempMin = 10000, tempMax = -1;
rows = image->height;
cols = image->width;
for(i = 0; i < (rows * cols); i++) if(tempMin > image->data[i]) tempMin = image->data[i];
for(i = 0; i < (rows * cols); i++) image->data[i] = image->data[i] - tempMin;
for(i = 0; i < (rows * cols); i++) if(tempMax < image->data[i]) tempMax = image->data[i];
for(i = 0; i < (rows * cols); i++) image->data[i] = (image->data[i] / (tempMax + 0.0));
}
int main(int argc, char *argv[]) {
I2D *im;
F2D *image;
int rows, cols, i, j;
F2D *frames;
unsigned int *startTime, *endTime, *elapsed;
char imSrc[100];
if(argc < 2) {
return -1;
}
sprintf(imSrc, "%s/1.bmp", argv[1]);
im = readImage(imSrc);
image = fiDeepCopy(im);
iFreeHandle(im);
rows = image->height;
cols = image->width;
startTime = photonStartTiming();
/** Normalize the input image to lie between 0-1 **/
normalizeImage(image);
/** Extract sift features for the normalized image **/
struct timespec clava_timing_start_0, clava_timing_end_0;
clock_gettime(CLOCK_MONOTONIC, &clava_timing_start_0);
frames = sift(image);
clock_gettime(CLOCK_MONOTONIC, &clava_timing_end_0);
double clava_timing_duration_0 = ((clava_timing_end_0.tv_sec + ((double) clava_timing_end_0.tv_nsec / 1000000000)) - (clava_timing_start_0.tv_sec + ((double) clava_timing_start_0.tv_nsec / 1000000000))) * (1000);
printf("%fms\n", clava_timing_duration_0);
endTime = photonEndTiming();
elapsed = photonReportTiming(startTime, endTime);
photonPrintTiming(elapsed);
free(startTime);
free(endTime);
free(elapsed);
fFreeHandle(frames);
return 0;
}
|
C | /*Instruction: int solveMeFirst(int a, int b);
where,
a is the first integer input.
b is the second integer input
Return values
sum of the above two integers
Sample Input
a = 2
b = 3
Sample Output
5*/
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int solveMeFirst(int a, int b) {
// Hint:sum and return value
}
int main() {
int num1,num2;
scanf("%d %d",&num1,&num2);
int sum;
sum = solveMeFirst(num1,num2);
printf("%d",sum);
return 0;
}
|
C | #include <stdio.h>
short map[2005][2005];
int main() {
int m, n;
int x, y, i, j;
while (1) {
scanf("%d %d", &n, &m);
if (n == 0 && m == 0) {
return ;
}
scanf("%d %d", &x, &y);
memset(map, 0, sizeof(map));
for (i = 0; i < n; i++) {
getchar();
for (j = 0; j < m; j++) {
if (getchar() == '*') {
map[i][j] = 1;
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.