-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashTables.js
More file actions
111 lines (85 loc) · 2.78 KB
/
HashTables.js
File metadata and controls
111 lines (85 loc) · 2.78 KB
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
//A hash table in a nutshell is an object that stores data in key value pairs
//Hash tables have a problem, it is called collisions
const user = {
age: 20,
name: 'Bob',
rich: true,
flex: function() {
console.log('racks on racks');
}
}
const a = new Map();
const b = new Set();
class HashTable {
constructor(size) {
this.data = new Array(size);
}
hash(key) {
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash = (hash + key.charCodeAt(i) * i) % this.data.length;
}
return hash;
}
set(key, value) {
let address = this.hash(key);
if(!this.data[address]) {
this.data[address] = [];
}
this.data[address].push([key, value]);
return this.data;
}
get(key) {
let address = this.hash(key);
const currentBucket = this.data[address];
console.log(currentBucket);
if(currentBucket) {
for(let i = 0; i< currentBucket.length; i++) {
if(currentBucket[i][0] == key) {
return currentBucket[i][1];
}
}
}
return undefined;
}
keys() {
const keysArray = [];
for (let i = 0; i < this.data.length; i++) {
if(this.data[i]) {
keysArray.push(this.data[i][0][0]);
}
}
return keysArray;
}
}
const myHashTable = new HashTable(50);
myHashTable.set('grapes', 10000);
myHashTable.set('apples', 200);
myHashTable.set('oranges', 300);
myHashTable.set('bannanas', 100);
myHashTable.set('bannanas', 100);
console.log(myHashTable.data);
console.log(myHashTable.keys());
//Summary
//A hash table is an array with a fixed length that uses hashes keys
//The keys are then used to index that array
//in each index a bucket (another array) is stored
//Sometimes there can be collisions, they are instances of when a different key has the same hash
//The bucket then stores key value pairs in an array.
//Problem Statement: Given an array of numbers, find the first number that is recurring
//First we need to create an empty Set object
//Second we will need to loop through the entire array
//Third we will check whether the Set object has the value stored already. If true, return the value
//If not, then we will add the current element into the Set.
//Finally, at the end of the function, if the lenght of the Set is equal to the length of the input array, we will return undefined.
const findRecurringNumber = function(arr) {
let mySet = new Set();
for (let i = 0; i < arr.length; i++) {
if (mySet.has(arr[i])) {
return arr[i];
}
else mySet.add(arr[i]);
}
return undefined;
}
console.log(findRecurringNumber([2,1,2,1]));