How do I calculate similarity of two integers?
c#
Solution
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;
}
Note: it does not handle negative integers
Update: fixed after question update
Problem
Actually it's quite hard to describe: I want to implement an algorithm which compares figure by figure of the same position (as I do my calculations in a 10-based system it's rather the same "power of ten") of two given integers/number (with the same "length"). It should return the grade of equality as following: - 4491 and 1020 = 0 - 4491 and 4123 = 1 - 4491 and 4400 = 2 - 4491 and 4493 = 3 - 4491 and 4491 = 4 - 4491 and 4091 = 1 I do not want to do my calculations based on a string-comparison, as I'll doing this in a way bigger scenario :)