Created
October 9, 2018 08:22
-
-
Save mebjas/ddaac345a80604d34cacfd712730d69f to your computer and use it in GitHub Desktop.
Way to hash map string to int in weighted hash manner
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace TestBench | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
int listCount = 1000000; | |
int bucketSize = 10; | |
string prefix = "prefix"; | |
SortedDictionary<int, int> histogram = new SortedDictionary<int, int>(); | |
for (int i = 0; i < listCount; i++) | |
{ | |
int k = GetHash(prefix + i.ToString(), bucketSize); | |
if (histogram.ContainsKey(k)) | |
{ | |
histogram[k]++; | |
} | |
else | |
{ | |
histogram[k] = 1; | |
} | |
} | |
foreach (KeyValuePair<int, int> pair in histogram) | |
{ | |
Console.WriteLine("{0}\t\t{1}\t\t{2}", pair.Key, pair.Value, (float)((float)pair.Value / (float)listCount)); | |
} | |
Console.ReadKey(); | |
} | |
static int GetHash(string s, int max) | |
{ | |
int k = Math.Abs(s.GetHashCode() % max); | |
if (k <= 3) | |
{ | |
return 0; | |
} | |
else if (k <= 6) | |
{ | |
return 1; | |
} | |
else if (k <= 8) | |
{ | |
return 2; | |
} | |
return 3; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment