Ruby / Rails按每个项目的相似性排序数组

时间:2014-02-27 05:42:11

标签: ruby arrays algorithm sorting

鉴于有几个名为A, A1, A2, A3, A4,的用户,每个用户都有一些书籍。

A  has books: B1, B2, B3, B4, B5   
A1 has books: B2, B4  
A2 has books: B3, B4, B5, B6  
A3 has books: B1, B3, B5
A4 has books: B1, B6

ruby​​ / rails对象的关系是:

+ User.class  
+ Book.class

用户有很多书,一本书属于用户,所以我们有user.books和book.user。

问题

问题是如何使用Ruby对用户(A1,A2,A3,A4)进行排序,其中用户A的书籍最常见。

结果

结果应该是[A2, A3, A1, A4]或类似的东西。

希望你们能帮我用Ruby / Rails实现这个算法。

1 个答案:

答案 0 :(得分:3)

我怀疑以OP建议的方式使用常量在任何方面都是有用的,因为你必须查看对象id来告诉哪个对象是哪个,但要实现OP要求的内容:

class User; attr_accessor :books end
class Book end

B1 = Book.new
B2 = Book.new
B3 = Book.new
B4 = Book.new
B5 = Book.new
B6 = Book.new
A = User.new
A1 = User.new # => #<User:0x007f38ddb8a890>
A2 = User.new # => #<User:0x007f38ddb8a458>
A3 = User.new # => #<User:0x007f38ddb8a070>
A4 = User.new # => #<User:0x007f38ddb89c38>
A.books = [B1, B2, B3, B4, B5]
A1.books =[B2, B4]
A2.books =[B3, B4, B5, B6]
A3.books =[B1, B3, B5]
A4.books = [B1, B6]

[A1, A2, A3, A4].sort_by{|user| (user.books & A.books).length}.reverse

结果

[
  #<User:0x007f38ddb8a070 @books=[#<Book:0x007f38ddb8a9d0>, #<Book:0x007f38ddb8a980>, #<Book:0x007f38ddb8a930>]>,
  #<User:0x007f38ddb8a458 @books=[#<Book:0x007f38ddb8a980>, #<Book:0x007f38ddb8a958>, #<Book:0x007f38ddb8a930>, #<Book:0x007f38ddb8a908>]>,
  #<User:0x007f38ddb8a890 @books=[#<Book:0x007f38ddb8a9a8>, #<Book:0x007f38ddb8a958>]>,
  #<User:0x007f38ddb89c38 @books=[#<Book:0x007f38ddb8a9d0>, #<Book:0x007f38ddb8a908>]>,
]