forked from Hunterhal/C-Programming-Examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
covid_tree.c
127 lines (98 loc) · 2.62 KB
/
covid_tree.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
typedef struct node{
int key;
char date[11];
int cases;
int deaths;
struct node *left, *right;
}node_t;
void insert(node_t **node_ref, int key, char *date, int cases, int deaths)
{
if(*node_ref == NULL)
{
*node_ref = malloc(sizeof(node_t));
(*node_ref)->key = key;
strcpy((*node_ref)->date, date);
(*node_ref)->cases = cases;
(*node_ref)->deaths = deaths;
(*node_ref)->left = NULL;
(*node_ref)->right = NULL;
return;
}
if( key <= (*node_ref)->key )
{
insert( &((*node_ref)->left), key, date, cases, deaths );
}
else if( key > (*node_ref)->key )
{
insert( &((*node_ref)->right), key, date, cases, deaths );
}
}
void print_inorder(node_t *node_ref)
{
if(node_ref == NULL)
return;
print_inorder(node_ref->left);
printf("%d ", node_ref->key);
print_inorder(node_ref->right);
}
void print_preorder(node_t *node_ref)
{
if(node_ref == NULL)
return;
printf("Key: %d ", node_ref->key);
printf("Date: %s, Cases: %d, Deaths: %d\n", node_ref->date, node_ref->cases, node_ref->deaths);
print_preorder(node_ref->left);
print_preorder(node_ref->right);
}
void print_postorder(node_t *node_ref)
{
if(node_ref == NULL)
return;
print_postorder(node_ref->left);
print_postorder(node_ref->right);
printf("%d ", node_ref->key);
}
void func(node_t **ptr_ref, node_t *ptr)
{
printf("Pointer is: %X, pointer adress is %X\n", ptr, &ptr);
printf("Pointer ref: %X, pointer ref holds: %X\n", ptr_ref, *ptr_ref);
}
//Calculating Hash, using %100 modulo 100 is not efficient used for demonstrating
int calculate_key(char *buffer)
{
unsigned long hash = 5381;
int c;
while (c = *buffer++)
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return hash%59;
}
void main()
{
node_t *tree = NULL;
FILE *f;
char buffer[30];
char date[10];
int cases;
int deaths;
int key;
printf("Tree: %X\n", &tree);
func(&tree, tree);
//open the file for reading
f = fopen("covid.txt", "r");
while(!feof(f))
{
fgets(buffer, 30, f);
sscanf(buffer, "%s %d %d\n", date, &cases, &deaths);
key = calculate_key(date);
insert(&tree, key, date, cases, deaths);
}
print_preorder(tree);
puts("");
print_inorder(tree);
puts("");
print_postorder(tree);
}