【问题标题】:Similar Array items but not exact ruby类似的数组项目,但不是确切的红宝石
【发布时间】:2014-05-02 23:20:42
【问题描述】:

我想看看我是否可以检查 2 个具有相似值的数组,并返回这 2 个数组之间不同的项目。但是我有名称相似的项目,我也希望将这些项目排除在外。 示例:

pantry = ["apples", "chedder cheese mild", "flour", "salt"] 
recipe = ["bacon", "chedder cheese sharp", "flour", "chocolate"]
#=> desired return ["apples","bacon", "chocolate", "salt"]

我使用pantry - recipe #=> ["apples", "bacon", "chocolate", "salt", "cheddar cheese mild"]得到的结果

【问题讨论】:

  • 无法复制。
  • 基本上你是在寻求魔法,这里所说的魔法是指没有大量工作就无法实现的事情(比如使用 ElasticSearch)。
  • 从期望的返回值中删除 "chedder cheese sharp" 和 "chedder cheese mild" 背后的逻辑是什么?
  • 在"bacon" 之前有"apples" 而在"chocolate" 之后有"salt" 背后的逻辑是什么? pantry 和 recipe 中的顺序是否重要?它们总是一样大吗?
  • 您需要以编程方式定义“相似”的含义,然后这将相当容易。

标签: ruby-on-rails ruby arrays algorithm sorting


【解决方案1】:

如果我们假设“相似”意味着除了最后一个单词之外的所有单词都相同的多单词字符串......

pantry = ["apples", "chedder cheese mild", "flour", "salt"]
recipe = ["bacon", "chedder cheese sharp", "flour", "chocolate"]

result = (pantry + recipe).group_by{|x| x.slice(0,(x.index(/[\s][^\s]+\z/) || x.size))}
result = result.values.select{|x|x.size == 1}.flatten.sort
=> ["apples", "bacon", "chocolate", "salt"]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-02
    • 1970-01-01
    • 2012-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多