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 :
Get an array with all combinations of the criteria possible ordered by score. In this case I should have : [['category', 'size', 'weigth'], ['category','size'], ['category', 'weight']开发者_开发百科, ['category'], ['size', 'weight'], ['size'], ['weight] ] ( the corresponding scores are : 26, 23, 18, 15, 11, 8, 3 )
Then make a unique request with all the combinations in order with a UNION between each combination and a limit 10 at the end. The sql request will be something like :
(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?
- And that's it I can link the results with my current item.
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.
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.
精彩评论