guts
guts

Reputation: 381

algorithm ruby (rails) array of best scores

I'm trying to link some ( ten ) items with another one. To choose the items I have some criteria that are attributes of my item (let's say "category", "size" and "weight"). Each of these criteria have a score (let's say 15 for category, 8 for size and 3 for weight).

My idea to find then ten best items to link with the current was something like that :

(Select * From items Where category = "food" and size = "3" and weight = "7")
UNION
(Select * From items where category = "food" and size = "3")
UNION
(.....)
limit 10;

I have tested this request and it seems to work well. The idea is that the important requests are the first so the results of the firsts requests are in the top and the limit 10 will just keep the most relevant results. But in telling that I have some doubt it can works on other database (it works on mysql but i'm not sure it will work with PostGreSQL). What do you think of that?

My problem is in the first point I don't know how to have this ordered array with all criteria combinations.

If you've got an idea I will take it ^^

Thank you in advance.

Upvotes: 0

Views: 381

Answers (1)

Michael Kohl
Michael Kohl

Reputation: 66837

Updated as per @tokland's comment.

Here's how you can create an array of combinations:

>> a = [*1..3] 
#=> [1, 2, 3]
>> b = (1..a.size).map { |n| a.combination(n).to_a }.flatten(1) 
#=> [[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]

In another step you can map, combine and sort.

Upvotes: 2

Related Questions