vendredi 21 juillet 2017

Consistent weighted mapping in Ruby

So I currently have the below method which randomly returns a string (of a known set of strings) based on a probability weight (based on this):

def get_response(request)
  responses = ['text1', 'text2', 'text3', 'text4', 'text5', 'text6']
  weights = [5, 5, 10, 10, 20, 50]
  ps = weights.map { |w| (Float w) / weights.reduce(:+) }
  # => [0.05, 0.05, 0.1, 0.1, 0.2, 0.5]

  weighted_response_hash = responses.zip(ps).to_h
  # => {"text1"=>0.05, "text2"=>0.05, "text3"=>0.1, "text4"=>0.1, "text5"=>0.2, "text6"=>0.5}

  response = weighted_response_hash.max_by { |_, weight| rand ** (1.0 / weight) }.first

  response
end

Now instead of a random weighted output, I want the output to be consistent based on an input string while keeping the weighted rate of response. So for example, a call such as:

get_response("This is my request")

Should always produce the same output, while keeping the weighted probability of the output text.

I think Modulo can be used here in some way, hash mapping to the same result but I'm kinda lost.




Aucun commentaire:

Enregistrer un commentaire