Skip to content

Instantly share code, notes, and snippets.

@foliea
Created April 3, 2025 09:34
Show Gist options
  • Select an option

  • Save foliea/d686463a6d410fb1058ab309bc209ab6 to your computer and use it in GitHub Desktop.

Select an option

Save foliea/d686463a6d410fb1058ab309bc209ab6 to your computer and use it in GitHub Desktop.
def euclidean_distance(flat, target, criteria)
sum_of_squares = criteria.sum do |criterion|
(flat[criterion] - target[criterion]) ** 2
end
Math.sqrt(sum_of_squares)
end
def rank_flats(flats, target)
criteria = target.keys
flats_with_proximity = flats.map do |flat|
proximity = euclidean_distance(flat, target, criteria)
{ flat: flat, proximity: proximity }
end
flats_with_proximity.sort_by { |flat| flat[:proximity] }
end
flats = [
{ id: 1, price: 20, size: 40, location: 5 },
{ id: 2, price: 40, size: 60, location: 8 },
{ id: 3, price: 60, size: 80, location: 7 },
{ id: 4, price: 70, size: 100, location: 6 }
]
target = { price: 45, size: 75 }
puts rank_flats(flats, target)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment