Skip to content

Instantly share code, notes, and snippets.

@VegaFromLyra
Last active August 29, 2015 14:24
Show Gist options
  • Save VegaFromLyra/f2a3d64f027600c6c59a to your computer and use it in GitHub Desktop.
Save VegaFromLyra/f2a3d64f027600c6c59a to your computer and use it in GitHub Desktop.
Generic Hash Map
using System;
using System.Collections.Generic;
namespace HashMapImplementation
{
public class Program
{
public static void Main(string[] args)
{
int n = 5;
var hashMap = new HashMap<string, string>(n);
hashMap.Add("test1", "aint");
hashMap.Add("test1", "no");
hashMap.Add("test2", "thing");
test(hashMap, "test1");
test(hashMap, "test2");
test(hashMap, "test3");
}
static void test(HashMap<string, string> hashMap, string key) {
try {
Console.WriteLine("hashMap[{0}] = {1}", key, hashMap.Get(key));
} catch(Exception e) {
Console.WriteLine("Error: {0} for {1}", e.Message, key);
}
}
}
class HashMap<K, V> {
List<List<Tuple<K, V>>> table;
int N;
public HashMap(int n) {
table = new List<List<Tuple<K, V>>>();
N = n;
for(int i = 0; i < N; i++) {
table.Add(new List<Tuple<K, V>>());
}
}
public void Add(K key, V value) {
int index = position(key);
var bucket = table[index];
foreach(var item in bucket) {
if (EqualityComparer<K>.Default.Equals(item.Key, key)) {
item.Value = value;
return;
}
}
bucket.Add(new Tuple<K, V>(key, value));
}
public V Get(K key) {
int index = position(key);
var bucket = table[index];
foreach(var item in bucket) {
if (EqualityComparer<K>.Default.Equals(item.Key, key)) {
return item.Value;
}
}
throw new Exception("Key not found");
}
int position(K key) {
return Math.Abs(key.GetHashCode()) % N;
}
}
class Tuple<K, V> {
public Tuple(K key, V value) {
this.Key = key;
this.Value = value;
}
public K Key { get; private set; }
public V Value { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment