Udemy: Master Coing Interview - Hash Tables - #78

Run Settings
LanguageC#
Language Version
Run Command
using System; using System.Collections.Generic; class HashTable { public struct KeyValue { public string key; public int value; } public LinkedList<KeyValue>[] data; public int size; static void Main() { Console.WriteLine("Hello World!"); HashTable myHashTable = new HashTable(2); myHashTable.Set("grapes", 10000); myHashTable.Set("grapes1", 10001); myHashTable.Set("grapes2", 10002); myHashTable.Set("grapes3", 10003); Console.WriteLine("Hash('grapes') = " + myHashTable.Get("grapes")); Console.WriteLine("Hash('grapes1') = " + myHashTable.Get("grapes1")); Console.WriteLine("Hash('grapes2') = " + myHashTable.Get("grapes2")); Console.WriteLine("Hash('grapes3') = " + myHashTable.Get("grapes3")); Console.WriteLine("Keys = " + ToString(myHashTable.Keys())); } public static string ToString(string[] strings) { string s = "{"; int count = 0; foreach (string str in strings) { if (count > 0) { s += ", "; } s += str; count++; } s += "}"; return s; } public HashTable(int size) { this.data = new LinkedList<KeyValue>[size]; this.size = size; } public void Set(string key, int value) { int address = this.Hash(key); if (this.data[address] == null) { this.data[address] = new LinkedList<KeyValue>(); } KeyValue kv = new KeyValue(); kv.key = key; kv.value = value; this.data[address].AddLast(kv); } public int Get(string key) { int address = this.Hash(key); if (this.data[address] != null) { foreach (KeyValue kv in this.data[address]) { if (kv.key == key) { return kv.value; } } } return 0; } public string[] Keys() { string[] temp = new string[100]; int keyCount = 0; for (int i = 0; i < this.data.Length; i++) { if (this.data[i] != null) { foreach (KeyValue kv in this.data[i]) { temp[keyCount] = kv.key; keyCount++; } } } string[] keys = new string[keyCount]; for (int i = 0; i < keyCount; i++) { keys[i] = temp[i]; } return keys; } private int Hash(string key) { int position = key.GetHashCode() % size; return Math.Abs(position); // int hashValue = 0; // for (int i = 0; i < key.Length; i++) { // hashValue = (hashValue + (int)key[i] * i) % this.data.Length; // } // return hashValue; } }
Editor Settings
Theme
Key bindings
Full width
Lines