Last active
August 29, 2015 14:18
-
-
Save hobbes7878/0c3b2da1e49b8b6ddb7f to your computer and use it in GitHub Desktop.
A function to calculate the nearest match based on a shared set of ratings.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function manhattan(userRating, matchRating){ | |
/* | |
Calculates the manhattan distance between two ratings sets. | |
ratings are objects like this: | |
{speed:1, fitness:3, likeability:6} | |
We assume both sets have the same ratings categories, just different scores. | |
*/ | |
var distance = 0; | |
for (rating in userRating){ | |
distance = distance + Math.abs(userRating[rating] - matchRating[rating]) | |
} | |
return distance; | |
} | |
function nearest(user, matches){ | |
/* | |
Finds the nearest match according to a user's ratings. | |
Let's assume user is an anonymous object with ratings like | |
{goatee: 2, movieFacts: 7 ... } | |
And that matches is an array of named ratings like: | |
[ { name: John, | |
ratings: {goatee: 10, movieFacts: 0 ... } }, | |
{ name: Layne, | |
ratings: {goatee:0, movieFacts:9 ... } }, | |
... | |
] | |
*/ | |
var distances = []; | |
for(i in matches){ | |
distance = manhattan(user, matches[i].ratings) | |
distances.push( [matches[i].name, distance] ) | |
} | |
return distances.sort(function(a,b){ return a[1] - b[1]; })[0] | |
} | |
/*------------------------------------------------------*/ | |
/*Example*/ | |
var jon = {javascript:4, python:9, php:0, r:6, css:6, html:6, design: 0}, | |
guys = [ | |
{name: 'John', | |
ratings: {javascript:8, python:4, php:0, r:0, css:10, html:10, design: 8} }, | |
{name: 'Troy', | |
ratings: {javascript:7, python:5, php:0, r:0, css:10, html:10, design: 10} }, | |
{name: 'Layne', | |
ratings: {javascript:10, python:4, php:6, r:0, css:7, html:10, design: 8} }, | |
{name: 'Daniel', | |
ratings: {javascript:5, python:10, php:5, r:6, css:2, html:6, design: 0} }, | |
]; | |
nearest(jon, guys); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment