Skip to content

Instantly share code, notes, and snippets.

@mebjas
Created October 9, 2018 08:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mebjas/ddaac345a80604d34cacfd712730d69f to your computer and use it in GitHub Desktop.
Save mebjas/ddaac345a80604d34cacfd712730d69f to your computer and use it in GitHub Desktop.
Way to hash map string to int in weighted hash manner
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