using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Consistent_Hash
{
class Program
{
static void Main(string[] args)
{
int Server = Convert.ToInt32(Console.ReadLine());
int Data = Convert.ToInt32(Console.ReadLine());
int VirtualNode = Convert.ToInt32(Console.ReadLine());
ConsistentHash result =new ConsistentHash(Data,Server,VirtualNode);
int[] Tre = new int[10];
Tre = result.GetConsistentHash();
int AvNum = Data/Server;
int temp=0;
for (int i=0;i< Server; i++)
{
temp += Convert.ToInt32(Math.Pow(Tre[i] - AvNum, 2));
}
int STDev = Convert.ToInt32(Math.Sqrt(temp / Server));
for (int j=0; j<Server;j++)
{
Console.WriteLine("Server {0} 上分布了 {1} 组数据",j,Tre[j]);
}
Console.WriteLine("在拥有 {0} 台服务器,{1} 组KV数据,使用 {2} 个虚拟节点的情况下,数据在服务器上分布的标准差为 {3}", Server, Data, VirtualNode, STDev);
Console.ReadLine();
}
public class ConsistentHash
{
private int data;
private int server;
private int virtualNode;
public ConsistentHash(int data, int server, int virtualNode)
{
this.data = data;
this.server = server;
this.virtualNode = virtualNode;
}
public int[] GetConsistentHash()
{
int[] Snode =new int[server];
int To_server;
int i;
for ( i = 0; i < data; i++)
{
To_server = Convert.ToInt32((Math.Abs(i.ToString().GetHashCode())%(server * virtualNode))/virtualNode);
Snode[To_server] += 1;
}
return Snode;
}
}
}
}
评论