I need to get the match rate of two arrays based in their values.
Let's say I have an array of [9]
and another one of [9]
my match rate would be 100%. If one array is [9]
and the other is [4]
the rate would be 50%. If array one is [4, 3]
and array two is [4,3]
the rate is 100%.
I am not quire sure on how to sole this in order to get the rate back. The values in the array are only between 0-9 and are always in order. So the first item of array one should be matched with the first item of array two etc.
I am using ruby (on rails) but I think the question is more generic.
Thank you!
CodePudding user response:
Though I don't understand why [9]
and [4]
give 50%
but if [9]
and [4]
would return 0 than you can do it this way:
def arrays_rate(a, b)
return 100 if a.empty? && b.empty?
((a & b).size.to_f / [a, b].map(&:size).max) * 100
end
a = [9]
b = [9]
arrays_rate(a, b)
# => 100
a = [9]
b = [4]
arrays_rate(a, b)
# => 0
a = [9, 4]
b = [4, 3]
arrays_rate(a, b)
# => 50
a = [9, 4, 1]
b = [4, 9, 2]
arrays_rate(a, b)
# => 66.6
a = [9, 4, 1]
b = [4, 9, 2, 5, 6]
arrays_rate(a, b)
# => 40
CodePudding user response:
You could write the following.
def match_rate(a1,a2)
100.0 - (10.0/a1.size) * a1.zip(a2).sum { |a1,a2| (a1-a2).abs }
end
match_rate([9], [9]) #=> 100.0
match_rate([9], [4]) #=> 50.0
match_rate([4,3], [4,3]) #=> 100.0
match_rate([4,3], [4,2]) #=> 95.0
match_rate([4,3], [3,4]) #=> 90.0
match_rate([1,2,3,4,5], [1,-2,3,-4,5]) #=> 76.0
I've assumed that a1
and a2
are non-empty arrays of the same size. If desired, you could of course confirm that in the method.
Suppose
a1 = [4,6,2]
a2 = [7,6,5]
Then
a = 10.0/a1.size
#=> 3.3333333333333335
b = a1.zip(a2)
#=> [[4, 7], [6, 6], [2, 5]]
c = b.sum { |a1,a2| (a1-a2).abs }
#=> 3 0 3 => 6
d = a * c
#=> 20.0
100.0 - d
#=> 80.0