summaryrefslogtreecommitdiff
path: root/algorithms/ranking-dist.rb
blob: c621bdd3e5dc2e65ea711f6097a967e52957dac4 (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

items  = [0, 1, 2] 
ranks  = [1, 2, 3]
#permutations = [
#  [1,2,3],
#  [2,3,1],
#  [3,1,2],
#  [3,2,1],
#  [1,3,2]
#]
scores = [3, 2, 1]

def f items, ranks, scores,topone=false
  prod = 1
  items.each_with_index { |i,j|
    x = []
    d = Math.exp(scores[ranks[i]-1])
    x << ranks[i]
    sum = 0
    if j+1 <= items.size
      (j).upto(items.size-1) { |k|
        sum = sum+Math.exp(scores[ranks[k]-1])
        x << ranks[k]
      }
      prod = prod*(d/sum)
      if topone
        return  prod
      end
      puts "#{ranks[i]} / #{x[1..-1].map { |z| "#{z}" }.join(" ")}"
    end
  }
  return prod
end

#best = f items,ranks,scores

permutations = {}
sz = 0
stop = 0
while true
  break if stop == 1000
  r = ranks.shuffle
  permutations[r] = 1
  if sz == permutations.size
    stop = stop+1
  else
    sz = permutations.size
    stop = 0
  end
end

puts permutations.to_s

sumtoone = 0
permutations.each_key { |r|
  p = f items,r,scores,false
  puts "#{r.to_s} #{p}"
  puts
  sumtoone = sumtoone+p
  #if p >= best
  #  puts r.to_s
  #  puts p
  #end
}

puts "==="
puts sumtoone

puts "+++ NLL"

scores = [0.1,0.1,100]
true_ranking = [2,1,3]
puts(-Math.log(f(items,true_ranking,scores)))