summaryrefslogtreecommitdiff
path: root/kendalls-tau
blob: c0c20be6b361217ac7f77772620a9076022e3b4a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env ruby

#################################################
# reads space delimted pairs of scores as input,
# outputs Kendall's τ
#################################################

def kendall_with_ties l
  concordant = 0
  disconcordant = 0
  tie_a = 0
  tie_b = 0
  l.each_with_index { |k,i|
    l[i+1,l.size].each_with_index { |m,j|
      if (k.first < m.first && k[1] < m[1]) ||
         (k.first > m.first && k[1] > m[1]) 
        concordant += 1
      elsif (k.first == m.first && k[1] != m[1])
        tie_a += 1
      elsif (k.first != m.first && k[1] == m[1])
        tie_b += 1
      else
        disconcordant += 1
      end
    }
  }
 
  return (concordant-disconcordant)/(Math.sqrt((concordant+disconcordant+tie_a)*(concordant+disconcordant+tie_b)))
end

def kendall l
  concordant = 0
  disconcordant = 0
  l.each_with_index { |k,i|
    l[i+1,l.size].each_with_index { |m,j|
      if (k.first <= m.first && k[1] <= m[1]) ||
         (k.first >= m.first && k[1] >= m[1]) 
        concordant += 1
      else
        disconcordant += 1
      end
    }
  }

 return (concordant-disconcordant)/(0.5 * l.size * (l.size-1))
end

def has_ties? l
  if l.map{ |p| p[1] }.uniq.size != l.size ||
     l.map{ |p| p[2] }.uniq.size != l.size
    return true
  end

  return false
end

def main
  l = []
  while line = STDIN.gets
    a,b = line.split
    l << [a.to_f, b.to_f]
  end
  
  v = -1
  if has_ties? l
    v = kendall_with_ties l
  else
    v = kendall l
  end

  puts v
end

main