Geohashing【难度:3级】:
答案1:
using System;
using System.Security.Cryptography;
using System.Text;
public class Kata
{
public static Tuple<double, double> GeoHashing(double dow, DateTime? date = null)
{
DateTime dt = date ?? DateTime.UtcNow.Date;
string newString = MakeString(dow, dt);
newString = CreateMD5(newString);
string firstHalf = newString.Substring(0, 16);
string secondHalf = newString.Substring(16, 16);
double firstHalfDouble = HexToDouble(firstHalf);
double secondHalfDouble = HexToDouble(secondHalf);
firstHalfDouble = Math.Round(firstHalfDouble, 6);
secondHalfDouble = Math.Round(secondHalfDouble, 6);
return new Tuple<double, double>(firstHalfDouble, secondHalfDouble);
}
public static double HexToDouble(string hex)
{
double res = 0;
for (int i = 0; i < hex.Length; i++)
{
int dec = Convert.ToInt32(hex[i].ToString(), 16);
res += dec * Math.Pow(16, -(i + 1));
}
return res;
}
public static string MakeString(double dow, DateTime date)
{
string newString = date.ToString("yyyy-MM-dd-");
newString += dow.ToString("0.00");
return newString;
}
public static string CreateMD5(string input)
{
using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
{
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hashBytes = md5.ComputeHash(inputBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("X2"));
}
return sb.ToString();
}
}
}
答案2:
using System;
using System.Security.Cryptography;
using System.Text;
public class Kata
{
public static Tuple<double, double> GeoHashing(double dow, DateTime? date = null)
{
DateTime dt = date ?? DateTime.UtcNow.Date;
string newString = makeString(dow, dt);
newString = CreateMD5(newString);
string firstHalf = newString.Substring(0, 16);
string secondHalf = newString.Substring(16, 16);
long firstHalfLong = Convert.ToInt64(firstHalf.Substring(0, 8), 16);
double firstHalfDouble = (double)firstHalfLong / Math.Pow(16, 8);
firstHalfDouble = Math.Round(firstHalfDouble, 6);
long secondHalfLong = Convert.ToInt64(secondHalf.Substring(0, 8), 16);
double secondHalfDouble = (double)secondHalfLong / Math.Pow(16, 8);
secondHalfDouble = Math.Round(secondHalfDouble, 6);
return new Tuple<double, double>(firstHalfDouble, secondHalfDouble);
}