如何计算两个整数的相似度?

问题描述 投票:5回答:6

实际上很难描述: 我想实现一个算法,它比较两个给定整数/数字(具有相同的“长度”)相同位置的数字(就像我在基于10的系统中进行的计算,它是相同的“10的幂”) )。它应该返回平等等级如下:

  • 4491和1020 = 0
  • 4491和4123 = 1
  • 4491和4400 = 2
  • 4491和4493 = 3
  • 4491和4491 = 4
  • 4491和4091 = 1

我不想基于字符串比较进行计算,因为我会以更大的方式做这个:)

c#
6个回答
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
投票

对于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

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;
}

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

0
投票

听起来像Levenshtein Distance是合适的。这是衡量两个字符串之间差异的标准方法。在您的情况下,字符串是数字的十进制表示。


-1
投票

我最好的计算方法是使用Euclidean Similarity。

请看这个链接:http://stackoverflow.com/questions/11555355/calculating-the-distance-between-2-points

© www.soinside.com 2019 - 2024. All rights reserved.