Skip to content

Instantly share code, notes, and snippets.

@acrookston
Created April 1, 2016 22:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acrookston/41c1266d69f4fd7a343775337b0d1cee to your computer and use it in GitHub Desktop.
Save acrookston/41c1266d69f4fd7a343775337b0d1cee to your computer and use it in GitHub Desktop.
module Enumerable
def normalize
magnitude = Math.sqrt(reduce(:+))
return self if magnitude.nan?
map { |x| x.to_f / magnitude }
end
def similarity(arr)
return 0.0 if arr.count != count
similarity = Math.sqrt(zip(arr).map { |d| d.first * d.second }.reduce(:+))
similarity.nan? ? 0.0 : similarity
end
def score
score = Math.sqrt(map { |d| d * d }.reduce(:+))
score.nan? ? 0.0 : score
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment