- Implementing hash tables
- 18 Apr 2016 10:25:10 am
- Last edited by lirtosiast on 18 Apr 2016 04:39:35 pm; edited 2 times in total
A hash table is a common data structure in which an unordered set of elements is stored. It is possible to tell whether an element is in the set in O(1) time, instead of O(n) for an array or O(log n) for a tree.
The simplest hash tables are arrays connected to a linked list. In this TI-BASIC implementation, we can make the linked list and the array in a complex list L3 and a real list L1, respectively. Our elements will be real numbers, and as a TI-BASIC list is limited to 999 elements, we can only store a few hundred elements. On monochrome/CSE calculators, there is also a memory restriction, as a 999-element complex list takes 18k out of the total 24k of user memory.
First, we need a hash function that assigns a number to one of say 257 buckets, from 1 to 257. Here's one possible function, just taking X mod 257.
Code:
In the following code, L1(B) is the pointer to L3 for bucket B. L3(A) has data in the real part, and a pointer to the next element in the complex part. Null is zero.
We can add an element X thusly:
Code:
This should take 10 or 20 ms on average when the hash table isn't too full.
We can also check if an element is in the set (untested):
Code:
The simplest hash tables are arrays connected to a linked list. In this TI-BASIC implementation, we can make the linked list and the array in a complex list L3 and a real list L1, respectively. Our elements will be real numbers, and as a TI-BASIC list is limited to 999 elements, we can only store a few hundred elements. On monochrome/CSE calculators, there is also a memory restriction, as a 999-element complex list takes 18k out of the total 24k of user memory.
First, we need a hash function that assigns a number to one of say 257 buckets, from 1 to 257. Here's one possible function, just taking X mod 257.
Code:
1+remainder(int(X),257
In the following code, L1(B) is the pointer to L3 for bucket B. L3(A) has data in the real part, and a pointer to the next element in the complex part. Null is zero.
We can add an element X thusly:
Code:
1+dim(L3->I
X->L3(I //imaginary part (pointer) already zero
1+remainder(int(X),257 //bucket number
If L1(Ans
Then
L1(Ans
While imag(L3(Ans
imag(L3(Ans
End
L3(Ans)+[i]I->L3(Ans
Else
I->L1(Ans
End
This should take 10 or 20 ms on average when the hash table isn't too full.
We can also check if an element is in the set (untested):
Code:
1+remainder(int(N),257
If L1(Ans
Then
L3(L1(Ans //initial element and pointer
While N!=real(Ans) and imag(Ans //while no match and not null
imag(Ans->I% //next pointer
L3(I%
End
N=real(Ans
Else
0
End