实际上很难描述:
我想实现一个算法,它比较两个给定整数/数字(具有相同的“长度”)相同位置的数字(就像我在基于10的系统中进行的计算,它是相同的“10的幂”) )。它应该返回平等等级如下:
我不想基于字符串比较进行计算,因为我将以更大的方式执行此操作:)
答案 0 :(得分:3)
public static int Compare(int i1, int i2)
{
int result = 0;
while(i1 != 0 && i2 != 0)
{
var d1 = i1 % 10;
var d2 = i2 % 10;
i1 /= 10;
i2 /= 10;
if(d1 == d2)
{
++result;
}
else
{
result = 0;
}
}
if(i1 != 0 || i2 != 0)
{
throw new ArgumentException("Integers must be of same length.");
}
return result;
}
注意:它不处理负整数
更新:问题更新后修复
答案 1 :(得分:1)
See the Answer to this SO Question
您可以通过第一种方法拆分数字并从第二种方法中获取相似性:
int[] GetIntArray(int num)
{
List<int> listOfInts = new List<int>();
while(num > 0)
{
listOfInts.Add(num % 10);
num /= 10;
}
listOfInts.Reverse();
return listOfInts.ToArray();
}
int GetSimilarity(int firstNo, int secondNo)
{
int[] firstintarray = GetIntArray(firstNo)
int[] secondintarray = GetIntArray(secondNo)
if (firstintarray.Count != secondintarray.Count)
{
throw new ArgumentException("Numbers Unequal in Length!");
}
int similarity = 0;
for(i = 0; i < firstintarray.Count; i++)
{
if (secondintarray[i] = firstintarray[i])
{
similarity++;
continue;
}
break;
}
}
现在你可以像这样比较两个int数组:
int Similarity = GetSimilarity(4491, 4461);// Returns 2
答案 2 :(得分:1)
对于X和Y不相等的所有情况:
Length - Math.Floor(Math.Log10(Math.Abs(X - Y)) + 1)
4491和1020
4 - Math.Floor(Math.Log10(Math.Abs(4491 - 1020)) + 1) = 0
4491和4493
4 - Math.Floor(Math.Log10(Math.Abs(4491 - 4493)) + 1) = 3
答案 3 :(得分:1)
在我上一次尝试之后试图从这个问题中挽救一些东西......
int Compare(int x, int y)
{
int pow10 = (int)Math.Pow(10, Math.Floor(Math.Log(Math.Max(x, y), 10)));
int matches = 0;
while(pow10 > 0 && (x / pow10) == (y / pow10))
{
matches++;
pow10 /= 10;
}
return matches;
}
答案 4 :(得分:0)
听起来Levenshtein Distance是合适的。这是衡量两个字符串之间差异的标准方法。在您的情况下,字符串是数字的十进制表示。
答案 5 :(得分:-1)
我觉得计算它的最好方法是使用Euclidean Similarity。
请参阅此链接:http://stackoverflow.com/questions/11555355/calculating-the-distance-between-2-points