/
WalletHashTable.cpp
115 lines (98 loc) · 2.7 KB
/
WalletHashTable.cpp
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
//
// Created by yolanda on 4/3/2019.
//
//
// Created by yolanda on 4/3/2019.
//
#include "WalletHashTable.h"
#include "Wallet.h"
#include <cstring>
#include <stdio.h>
#include <stdlib.h>
WalletHashTable::WalletHashTable(int size) {
int i = 0;
this->size = size;
this->wallets = (Wallet**)malloc(sizeof(Wallet*) * size);
/* Initialize the Tree Nodes with NULL */
for ( i = 0; i < this->size; i++ ) {
this->wallets[i] = NULL;
}
}
int WalletHashTable::findIfWalletNotFound(char *userId) {
int hash = hashFunction(userId);
if(this->wallets[hash] == NULL || this->wallets[hash]->findUserWallet(userId)) {
return 0;
}
else {
return 1;
}
}
int WalletHashTable::find(char *userId) {
int hash = hashFunction(userId);
if(this->wallets[hash] != NULL) {
if(this->wallets[hash]->find(userId)) {
return 1;
}
else {
return 0;
}
}
else {
return 0;
}
}
/* Insert CoinId */
int WalletHashTable::insert(char *userId, ListNode *head) {
/* Find the hash */
int hash = hashFunction(userId);
if(this->wallets[hash] == NULL) {
// Create the new list
this->wallets[hash] = new Wallet(userId, head);
}
else {
// Add a new node to the hashtable
this->wallets[hash]->insert(userId, head);
}
}
int WalletHashTable::getBalance(char *userId) {
int hash = hashFunction(userId);
this->wallets[hash]->getBalance(userId);
}
/* Add Money to the User Wallet */
void WalletHashTable::addToWallet(char *userId, char *coin, int amount) {
int hash = hashFunction(userId);
this->wallets[hash]->addToWallet(userId, coin, amount);
}
/* Subtract Money from the User Wallet */
void WalletHashTable::subtractFromWallet(char *userId, char *coin, int amount) {
int hash = hashFunction(userId);
this->wallets[hash]->subtractFromWallet(userId, coin, amount);
}
/* Print Wallet of a user */
void WalletHashTable::print(char *userId) {
int hash = hashFunction(userId);
this->wallets[hash]->printCoins(userId);
}
/* Hash Function for strings */
int WalletHashTable::hashFunction(char *userId) {
unsigned long hash = 5381;
int c;
while (c = *userId++)
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return hash % this->size;
}
WalletHashTable::~WalletHashTable() {
Wallet *current, *temp;
int i = 0;
for ( int i = 0; i < this->size; i++ ) {
if( this->wallets[i] != NULL ) {
current = this->wallets[i];
while(current != NULL) {
temp = current->getNext();
delete current;
current = temp;
}
}
}
free(this->wallets);
}