-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
87 lines (76 loc) · 2.19 KB
/
Program.cs
File metadata and controls
87 lines (76 loc) · 2.19 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
using System;
using System.Collections.Generic;
namespace Chaining;
class HashTableChaining
{
private int size;
private LinkedList<KeyValuePair<string, string>>[] table;
public HashTableChaining(int size)
{
this.size = size;
table = new LinkedList<KeyValuePair<string, string>>[size];
for (int i = 0; i < size; i++)
{
table[i] = new LinkedList<KeyValuePair<string, string>>();
}
}
private int HashFunction(string key)
{
int hash = key.GetHashCode();
return Math.Abs(hash) % size;
}
public void Insert(string key, string value)
{
int index = HashFunction(key);
foreach (var pair in table[index])
{
if (pair.Key == key)
{
Console.WriteLine($"Key '{key}' already exists.");
return;
}
}
table[index].AddLast(new KeyValuePair<string, string>(key, value));
Console.WriteLine($"Inserted ({key}, {value}) at index {index}");
}
public string Get(string key)
{
int index = HashFunction(key);
foreach (var pair in table[index])
{
if (pair.Key == key)
return pair.Value;
}
return null;
}
public void PrintTable()
{
for (int i = 0; i < size; i++)
{
Console.Write($"Index {i}: ");
foreach (var pair in table[i])
{
Console.Write($"[{pair.Key}, {pair.Value}] -> ");
}
Console.WriteLine("null");
}
}
}
class Program
{
static void Main(string[] args)
{
HashTableChaining ht = new HashTableChaining(5);
ht.Insert("Alice", "Matematika");
ht.Insert("Bob", "Fisika");
ht.Insert("Charlie", "Biologi");
ht.Insert("Dave", "Kimia");
ht.Insert("Eve", "Ekonomi");
Console.WriteLine("\nData yang diambil:");
Console.WriteLine("Alice: " + ht.Get("Alice"));
Console.WriteLine("Eve: " + ht.Get("Eve"));
Console.WriteLine("Frank: " + (ht.Get("Frank") ?? "Tidak ditemukan"));
Console.WriteLine("\nIsi Hash Table:");
ht.PrintTable();
}
}